Created
September 16, 2017 05:42
-
-
Save Deviad/d7469dacf4a20633387fbcdf9e2c84fd to your computer and use it in GitHub Desktop.
Hibernate - Stackoverflow generic error
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.davidepugliese.springfood.models; | |
import lombok.Data; | |
import lombok.Getter; | |
import lombok.Setter; | |
import lombok.ToString; | |
import javax.persistence.*; | |
import java.util.*; | |
@Data | |
@ToString | |
@Entity | |
@Table(name = "roles") | |
public class Role { | |
@ManyToMany(cascade = CascadeType.PERSIST) | |
@JoinTable( | |
name = "role_user", | |
joinColumns = @JoinColumn(name = "role_id"), | |
inverseJoinColumns = @JoinColumn(name = "user_id") | |
) | |
protected @Getter @Setter Set<User> users = new HashSet<>(); | |
@Id @GeneratedValue(strategy= GenerationType.AUTO) protected int id; | |
@Column(length = 255, unique = true, nullable=false) protected @Getter @Setter String role; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.davidepugliese.springfood.domain; | |
import com.davidepugliese.springfood.models.Role; | |
import com.davidepugliese.springfood.models.User; | |
import java.util.List; | |
public interface RoleDAO { | |
void saveRole(Role rolename); | |
List<User> getUsersByRole(String role); | |
List<String> getRoles(); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.davidepugliese.springfood.domain; | |
import com.davidepugliese.springfood.models.Role; | |
import com.davidepugliese.springfood.models.User; | |
import org.hibernate.Session; | |
import org.hibernate.SessionFactory; | |
import org.springframework.beans.factory.annotation.Autowired; | |
import org.springframework.stereotype.Repository; | |
import org.springframework.transaction.annotation.Transactional; | |
import javax.persistence.EntityManager; | |
import java.util.List; | |
@Transactional | |
@Repository | |
public class RoleDAOImpl implements RoleDAO { | |
private final SessionFactory sessionFactory; | |
private final EntityManager em; | |
@Autowired | |
public RoleDAOImpl(SessionFactory sessionFactory, EntityManager em) { | |
this.sessionFactory = sessionFactory; | |
this.em = em; | |
} | |
@Override | |
public void saveRole(Role theRole) { | |
// get current hibernate session | |
Session currentSession = sessionFactory.getCurrentSession(); | |
// save the customer ... finally LOL | |
currentSession.save(theRole); | |
} | |
@Override | |
@SuppressWarnings("unchecked") | |
//TODO: this query needs to be remade properly | |
public List<User> getUsersByRole(String rolename) { | |
String queryString = "FROM User u JOIN role_user where u.role = :rolename"; | |
return (List<User>) em.createQuery(queryString).setParameter("username", rolename).getResultList(); | |
} | |
@Override | |
@SuppressWarnings("unchecked") | |
public List<String> getRoles() { | |
String queryString = "FROM Role r"; | |
return (List<String>) em.createQuery(queryString).getResultList(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.davidepugliese.springfood.models; | |
import com.fasterxml.jackson.annotation.JsonIgnore; | |
import lombok.Data; | |
import lombok.Getter; | |
import lombok.Setter; | |
import lombok.ToString; | |
import javax.persistence.*; | |
import java.util.*; | |
@Data | |
@ToString | |
@Entity | |
@Table(name = "users") // necessary if you want the table to be named users instead of user | |
public class User { | |
@ManyToMany(mappedBy = "users") | |
protected @Getter @Setter Set<Role> roles = new HashSet<>(); | |
@Id @GeneratedValue(strategy= GenerationType.AUTO) protected int id; | |
@Column(length = 255, unique = true, nullable=false) protected @Getter @Setter String username; | |
@Column(length = 255, unique = true, nullable = false) protected @Getter @Setter String password; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.davidepugliese.springfood.controllers; | |
import com.davidepugliese.springfood.domain.UserDAO; | |
import com.davidepugliese.springfood.models.User; | |
import com.davidepugliese.springfood.security.Acl; | |
import com.davidepugliese.springfood.services.EncryptionUtilities; | |
import com.davidepugliese.springfood.adt.IEmail; | |
import com.fasterxml.jackson.annotation.JsonView; | |
import com.sun.javaws.exceptions.InvalidArgumentException; | |
import io.jsonwebtoken.Jwts; | |
import io.jsonwebtoken.SignatureAlgorithm; | |
import org.springframework.beans.factory.annotation.Autowired; | |
import org.springframework.beans.factory.annotation.Value; | |
import org.springframework.dao.DataIntegrityViolationException; | |
import org.springframework.http.HttpStatus; | |
import org.springframework.http.MediaType; | |
import org.springframework.http.ResponseEntity; | |
import org.springframework.ui.Model; | |
import org.springframework.web.bind.annotation.*; | |
import java.util.Date; | |
import java.util.HashMap; | |
import java.util.Map; | |
@RestController | |
@RequestMapping("/api/user/") | |
public class UserController { | |
@Value("${jwt.secret}") | |
private String secretKey; | |
private UserDAO userService; | |
@Autowired | |
public UserController(UserDAO userService) { | |
this.userService = userService; | |
} | |
@RequestMapping(value="/{id}", method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE) | |
public @ResponseBody | |
User getUser(@PathVariable Integer id) { | |
return userService.getUser(id); | |
} | |
@Acl("whatever") | |
@RequestMapping(value="/username/{username:.+}", method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE) | |
public | |
ResponseEntity getUserByUsername(@PathVariable String username, @RequestHeader(value="Authorization") String token) throws InvalidArgumentException { | |
Object user = userService.getUserByUsername(IEmail.create(username)); | |
System.out.println(">>>>>>BEGIN TESTTTTTTT<<<<<<<"); | |
System.out.println(user); | |
System.out.println(">>>>>>END TESTTTTT<<<<<<<"); | |
Map<String, Object> response = new HashMap<>(); | |
response.put("status", "success"); | |
response.put("data", user); | |
return ResponseEntity.ok(response); | |
} | |
@RequestMapping(value="/add", method=RequestMethod.POST, produces=MediaType.APPLICATION_JSON_VALUE) | |
@ResponseStatus( HttpStatus.CREATED ) | |
public | |
ResponseEntity addUser(@RequestBody User data, Model model) { | |
try { | |
User user = new User(); | |
user.setUsername(data.getUsername()); | |
user.setPassword(EncryptionUtilities.encryptPassword(data.getPassword())); | |
this.userService.saveUser(user); | |
Map<String, String> response = new HashMap<>(); | |
response.put("status", "success"); | |
response.put("message", "User created successfully"); | |
return ResponseEntity.ok(response); | |
} catch (DataIntegrityViolationException e) { | |
Map<String, String> response = new HashMap<>(); | |
response.put("status", "fail"); | |
response.put("reason", "Username exists already"); | |
return ResponseEntity.status(HttpStatus.NOT_ACCEPTABLE).body(response); | |
} | |
} | |
@RequestMapping(value="/login", method=RequestMethod.POST, produces=MediaType.APPLICATION_JSON_VALUE) | |
@ResponseStatus( HttpStatus.OK ) | |
public | |
ResponseEntity login(@RequestBody User login, Model model) { | |
String jwtToken; | |
if (login.getUsername() == null || login.getPassword() == null) { | |
Map<String, String> response = new HashMap<>(); | |
response.put("status", "fail"); | |
response.put("reason", "Insert username and password"); | |
return ResponseEntity.status(HttpStatus.NOT_ACCEPTABLE).body(response); | |
} | |
String email = login.getUsername(); | |
String password = login.getPassword(); | |
User user = userService.getUserByUsername(email); | |
if (user == null) { | |
Map<String, String> response = new HashMap<>(); | |
response.put("status", "fail"); | |
response.put("reason", "Username not found"); | |
return ResponseEntity.status(HttpStatus.NOT_ACCEPTABLE).body(response); | |
} | |
String pwd = user.getPassword(); | |
if (!EncryptionUtilities.matches(password, pwd)) { | |
Map<String, String> response = new HashMap<>(); | |
response.put("status", "fail"); | |
response.put("reason", "Wrong password"); | |
return ResponseEntity.status(HttpStatus.NOT_ACCEPTABLE).body(response); | |
} | |
jwtToken = Jwts.builder().setSubject(email).claim("roles", "user").setIssuedAt(new Date()) | |
.signWith(SignatureAlgorithm.HS256, secretKey).compact(); | |
Map<String, Object> response = new HashMap<>(); | |
Object status_message = "success"; | |
response.put("status", status_message); | |
response.put("data", jwtToken); | |
return ResponseEntity.ok(response); | |
} | |
} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.davidepugliese.springfood.domain; | |
import com.davidepugliese.springfood.models.Role; | |
import com.davidepugliese.springfood.models.User; | |
import java.util.List; | |
public interface UserDAO { | |
// public User getUser(); | |
void saveUser(User theUser); | |
User getUser(Integer id); | |
User getUserByUsername(String username); | |
List<Role> getRolesByUsername(String username); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.davidepugliese.springfood.domain; | |
import com.davidepugliese.springfood.models.Role; | |
import com.davidepugliese.springfood.models.User; | |
import org.hibernate.Session; | |
import org.hibernate.SessionFactory; | |
import org.springframework.beans.factory.annotation.Autowired; | |
import org.springframework.data.domain.Page; | |
import org.springframework.data.domain.Pageable; | |
import org.springframework.data.jpa.repository.Query; | |
import org.springframework.stereotype.Repository; | |
import org.springframework.transaction.annotation.Transactional; | |
import javax.persistence.EntityManager; | |
import java.util.List; | |
@Transactional | |
@Repository | |
public class UserDAOImpl implements UserDAO { | |
private final SessionFactory sessionFactory; | |
private final EntityManager em; | |
@Autowired | |
public UserDAOImpl(SessionFactory sessionFactory, EntityManager em) { | |
this.sessionFactory = sessionFactory; | |
this.em = em; | |
} | |
@Override | |
public void saveUser(User theUser) { | |
// get current hibernate session | |
Session currentSession = sessionFactory.getCurrentSession(); | |
// save the customer ... finally LOL | |
currentSession.save(theUser); | |
} | |
@Override | |
public User getUser(Integer theUserId) { | |
// get current hibernate session | |
String queryString = "FROM User u WHERE u.id = :theUserId"; | |
return (User) em.createQuery(queryString).setParameter("theUserId", theUserId).getSingleResult(); | |
} | |
@Override | |
public User getUserByUsername(String username) { | |
// get current hibernate session | |
String queryString = "FROM User u WHERE u.username = :username"; | |
return (User) em.createQuery(queryString).setParameter("username", username).getSingleResult(); | |
} | |
// SELECT op.username, op.email, orders.p_id, orders.o_id, product.listed_price | |
// FROM Orders order | |
// INNER JOIN order.orderProcessing as op | |
// INNER JOIN order.product as product | |
// ORDER BY op.username | |
@Override | |
@SuppressWarnings("unchecked") | |
public List<Role> getRolesByUsername(String username) { | |
String queryString = "SELECT r.role FROM User u JOIN u.roles as r where u.username = :username"; | |
return (List<Role>) em.createQuery(queryString).setParameter("username", username).getResultList(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment