I am new to JPA/Hibernate,
I am creating a simple join for getting some data in different table
Let's see like this:
The purpose is getting the M_PROFILE data based on M_USER.username column, but clearly you see that there is no foreign key in M_PROFILE table.
I just try to use below code but have no results and always got error.
User Entity Class
#Entity
#Table(name = "M_USER")
public class User {
#Id
#Column(name = "id")
private String uuid;
#Column(name = "email")
private String email;
#Column(name = "username")
private String username;
#OneToOne(fetch = FetchType.LAZY)
#MapsId("username")
private Profile profile;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Profile getProfile() {
return profile;
}
public void setProfile(Profile profile) {
this.profile = profile;
}
}
Profile Entity Class
#Entity
#Table(name = "M_PROFILE")
public class Profile {
private String username;
private String phone;
private String address;
#Id
#Column(name = "username", nullable = false)
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
#Basic
#Column(name = "phone")
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
#Basic
#Column(name = "address")
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
I got different error when calling
User user = userRepository.findByUsername("aswzen");
String phone = user.getProfile().getPhone();
for example this one.
"USER0_"."PROFILE_USERNAME": invalid identifier
Need help, thanks in advance,
NB : i don't have privilege to alter the table..
Don't forget to disable insertable and updatable for JoinColumn
#OneToOne
#JoinColumn(name = "username", referencedColumnName = "username", updatable = false, insertable = false)
private profile profile;
Try to specify a join column:
#OneToOne
#JoinColumn(name = "username", referencedColumnName = "username")
private profile profile;
You do not really need the #MapsId here.
I recommend create third table with relations for your tables
#Entity
#Table(name = "M_USER")
public class User {
#OneToOne(fetch = FetchType.LAZY)
#JoinTable(
name = "user_profile",
joinColumns = #JoinColumn(name="user_id"),
inverseJoinColumns = #JoinColumn(name="profile_username")
)
private Profile profile;
UPDATE user_profile
SET user_id = (
SELECT id
FROM M_USER
);
UPDATE user_profile
SET profile_username = (
SELECT username
FROM M_USER
);
Related
I have a user and a movie model:
user:
#Entity(name = "User")
#Table(name = "USER")
public class User {
#Id
#Column(name = "ID")
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "user_seq")
#SequenceGenerator(name = "user_seq", sequenceName = "user_seq", allocationSize = 1)
private Long id;
#Column(name = "USERNAME", length = 50, unique = true)
#NotNull
#Size(min = 4, max = 50)
private String username;
#Column(name = "PASSWORD", length = 100)
#NotNull
#Size(min = 4, max = 100)
private String password;
#Column(name = "FIRSTNAME", length = 50)
#NotNull
#Size(min = 4, max = 50)
private String firstname;
#Column(name = "LASTNAME", length = 50)
#NotNull
#Size(min = 4, max = 50)
private String lastname;
#Column(name = "EMAIL", length = 50)
#NotNull
#Size(min = 4, max = 50)
private String email;
#Column(name = "ENABLED")
#NotNull
private Boolean enabled;
#Column(name = "LASTPASSWORDRESETDATE")
#Temporal(TemporalType.TIMESTAMP)
#NotNull
private Date lastPasswordResetDate;
#ManyToMany(fetch = FetchType.EAGER)
#JoinTable(
name = "USER_AUTHORITY",
joinColumns = {#JoinColumn(name = "USER_ID", referencedColumnName = "ID")},
inverseJoinColumns = {#JoinColumn(name = "AUTHORITY_ID", referencedColumnName = "ID")})
private List<Authority> authorities;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Boolean getEnabled() {
return enabled;
}
public void setEnabled(Boolean enabled) {
this.enabled = enabled;
}
public List<Authority> getAuthorities() {
return authorities;
}
public void setAuthorities(List<Authority> authorities) {
this.authorities = authorities;
}
public Date getLastPasswordResetDate() {
return lastPasswordResetDate;
}
public void setLastPasswordResetDate(Date lastPasswordResetDate) {
this.lastPasswordResetDate = lastPasswordResetDate;
}
#ManyToMany(cascade = CascadeType.ALL)
#JoinTable(name = "user_movie",
joinColumns = #JoinColumn(name = "user_id", referencedColumnName = "id"),
inverseJoinColumns = #JoinColumn(name = "movie_id", referencedColumnName = "id")
)
private Set<Movie> movies;
public Set<Movie> getMovies() {
return movies;
}
public void setMovies(Set<Movie> movies) {
this.movies = movies;
}
}
movie:
#Entity(name = "Movie")
#Table(name = "movie")
public class Movie {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String name;
public Movie(){}
public Movie(Integer id, String name ) {
this.id = id;
this.name = name;
}
#ManyToMany(mappedBy = "movies")
private Set<User> users;
public Set<User> getUsers() {
return users;
}
public void addUser(User user){
System.out.println("ADD MOVIE: " + user);
users.add(user);
user.getMovies().add(this);
}
public void setUsers(Set<User> users) {
this.users = users;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public String toString(){
return "id: " + id + "name: " + name;
}
}
I've set up a many to many relation between these models. With, if I am correct, the user as the owner of the relation.
In my MovieController.java I have:
#RequestMapping(value = "/", method = RequestMethod.POST)
public Movie createMovie(#RequestBody Movie movie){
return movieService.createMovie(movie);
}
This calls the MovieService.java:
#Override
public Movie createMovie(Movie movie) {
return movieRepository.save(movie);
}
And this calls the MovieRepository.java:
#Repository
public interface MovieRepository extends CrudRepository<Movie, Serializable> {}
When I call the post methode from my front-end a movie record is saved in my movie table, but no record is created in the user_movie table. Doesn't Hibernate do this implicit since I set up a Many to Many relation between user and movie?
For the first view, your code is correct.
The problem can be in GenerationType.SEQUENCE (try to use GenerationType.AUTO for User's id), or you need to add #Transactional to your controller.
You save the movie and in order to also have the user saved the cascade has to be set in the movie. Otherwise you can keep the cascade in user and save him.
You need to put the cascade to the entity on which you call save to cascade it.
Movie{
#ManyToMany(mappedBy = "movies", cascade={CascadeType.ALL})
private Set<User> users;
public Set<User> getUsers() {
return users;
}
}
User {
#ManyToMany
#JoinTable(name = "user_movie",
joinColumns = #JoinColumn(name = "user_id", referencedColumnName = "id"),
inverseJoinColumns = #JoinColumn(name = "movie_id", referencedColumnName = "id")
)
private Set<Movie> movies;
}
Don't forget to add the user to movie and vice versa before saving.
As with all bi-directional relationships it is your object model's and application's responsibility to maintain the relationship in both direction. There is no magic in JPA, if you add or remove to one side of the collection, you must also add or remove from the other side, see object corruption. Technically the database will be updated correctly if you only add/remove from the owning side of the relationship, but then your object model will be out of synch, which can cause issues.
see here: https://en.wikibooks.org/wiki/Java_Persistence/ManyToMany
I am learning Spring and I can't find out how to map two models in Spring JPA. I was able to join table by ID. By default it links user.id. I want to link the user.userName. How to change it?
My User model:
#Entity
#Table(name = "user")
public class SiteUser {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id")
private Long id;
#Column(name = "username", unique = true, length = 30)
private String userName;
#Column(name = "email", unique = true, length = 60)
private String email;
#Column(name = "password", length = 60)
private String password;
#Column(name = "role", length = 15)
private String role;
#Column(name = "fullname", length = 60)
private String fullName;
#Column(name = "age", length = 3)
private int age;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
}
My Profile model:
#Entity
#Table(name="profile")
public class Profile {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="id")
private Long id;
#OneToOne(targetEntity=SiteUser.class)
#JoinColumn(name="user_id", nullable=false)
private SiteUser user;
#Column(name="about", length=5000)
private String about;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public SiteUser getUser() {
return user;
}
public void setUser(SiteUser user) {
this.user = user;
}
public void safeCopyFrom(Profile other){
if(other.about !=null){
this.about = other.about;
}
}
}
You are using a bidirectional #OneToOne relation between two entites and where you place your #JoinColumn indicates the owner side of relation that in your case you put it on Profile class.
Here is the great article about relationships between two entities, as it mentions
A Join Column in JPA is a column in the owner entity that refers to a key (usually a primary key) in the non-owner or inverse entity. The first thing that comes to mind after reading the above line is that JoinColumns are nothing but a Foreign Key Columns. And it is indeed the case. JPA calls them Join Columns, possibly because they are more verbose in what their actual role is, to join the two entities using a common column.
So you are defining a Foreing Key Column on Profile class
The rule of Foreing Key Column is that it should point to a Primary Key or a Unique Column in target entity and you should use it like this on you senario
public class Profile {
#OneToOne
#JoinColumn(name="username")
private SiteUser user;
}
I am trying to map between tables in pojo class.But I am getting exception for one attribute.
Pojo Classes
Users:
#Entity
#Table(name = "Users")
public class Users implements java.io.Serializable {
private int userId;
private Role role;
private Groups groupId;
private UserType userType;
private String userName;
private Boolean isActive;
public Users() {
}
public Users(int userId, Role role, Groups groupId ,UserType userType, String userName, boolean isActive) {
this.userId = userId;
this.role = role;
this.groupId = groupId;
this.userType = userType;
this.userName = userName;
this.isActive = isActive;
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "UserID", unique = true, nullable = false)
public int getUserId() {
return this.userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "RoleID", nullable = false)
public Role getRole() {
return this.role;
}
public void setRole(Role role) {
this.role = role;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "GroupId", nullable = false)
public Groups getGroup() {
return this.groupId;
}
public void setGroup(Groups group) {
this.groupId = group;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "UserTypeID", nullable = false)
public UserType getUserType() {
return this.userType;
}
public void setUserType(UserType userType) {
this.userType = userType;
}
#Column(name = "UserName", nullable = false)
public String getUserName() {
return this.userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
#Column(name = "IsActive", nullable = false, columnDefinition = "BIT")
public Boolean isIsActive() {
return this.isActive;
}
public void setIsActive(Boolean isActive) {
this.isActive = isActive;
}
}
Groups:
#Entity
#Table(name = "Groups")
public class Groups implements java.io.Serializable{
private int groupId;
private String groupName;
private String groupDesc;
private Set<Users> users = new HashSet<Users>(0);
public Groups (){
}
public Groups(int groupId, String groupName, String groupDesc){
super();
this.groupId = groupId;
this.groupName = groupName;
this.groupDesc = groupDesc;
}
public Groups(int groupId, String groupName, String groupDesc, Set<Users> users) {
super();
this.groupId = groupId;
this.groupName = groupName;
this.groupDesc = groupDesc;
this.users = users;
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name ="GroupID", nullable = false)
public int getGroupId() {
return groupId;
}
public void setGroupId(int groupId) {
this.groupId = groupId;
}
#Column(name = "GroupName", nullable = false)
public String getGroupName() {
return groupName;
}
public void setGroupName(String groupName) {
this.groupName = groupName;
}
#Column(name = "GroupDesc", nullable = false)
public String getGroupDesc() {
return groupDesc;
}
public void setGroupDesc(String groupDesc) {
this.groupDesc = groupDesc;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "groupId") //Error
public Set<Users> getUserse() {
return this.userse;
}
public void setUserse(Set<Users> users) {
this.users = users;
}
}
I am mapping the correct member variable of Users class. But I am getting exception like this
org.hibernate.AnnotationException: mappedBy reference an unknown target entity property: com.project.pojo.Users.groupId in com.project.pojo.Groups.users
In users pojo I have attributes like role,usertype which are mapped without any exception.Whereas for group I am getting this exception.
Can someone please help me to resolve this exception.
Thank you :)
There is a problem in your member variables of classes users and groups
Change the variable name groupId to group of Users.pojo and change mappedby attribute to group in groups class set method.
This will resolve your problem.
In your Groups class, you first declared a variable named users as a set of Users, which is fine. So if you gonna annotate #OneToMany on your setters, the name must match the variable name.
Also, in your Users table, you created a Groups variable and you named it as groupId, but in your Users table you have a int type named groupId, this will confuse the heck out of hibernate and causing problems. You should rename it to:
private Groups group;
So it should be like:
#OneToMany(fetch = FetchType.LAZY, mappedBy = "group")
public Set<Users> getUsers() {
return this.users;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "group", nullable = false)
public Groups getGroup() {
return this.group;
}
You didn't ask but you need to fix your RoleID table also. I don't think you really understand how hibernate ORM works yet, see this:
http://www.mkyong.com/hibernate/hibernate-one-to-many-relationship-example-annotation/
It must be because of difference between users and userse.
You defined getter for the Group object in Users bean as:
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "GroupId", nullable = false)
public Groups getGroup() {
return this.groupId;
}
which is not the best accessor name for a bean.
Try renaming the Group object in Users from groupID to group and change the mapping annotation into something like:
#OneToMany(fetch = FetchType.LAZY, mappedBy = "group")
public Set<Users> getUserse() {
return this.userse;
}
I have following entity classes:
#MappedSuperclass
public class AbstractEntity implements Serializable, Comparable<AbstractEntity> {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
protected Integer id;
#Override
public int compareTo(AbstractEntity o) {
return this.toString().compareTo(o.toString());
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
}
#Entity
#Table(name = "ticket")
#NamedQueries({
#NamedQuery(name = "Ticket.findAll", query = "SELECT t FROM Ticket t")})
public class Ticket extends AbstractEntity {
#Column(name = "title")
private String title;
#Column(name = "description")
private String description;
#Enumerated(EnumType.STRING)
#Column(name = "status")
private TicketStatus status;
#Enumerated(EnumType.STRING)
#Column(name = "priority")
private TicketPriority priority;
#Column(name = "categories")
private String categories;
#Column(name = "views")
private Integer views;
#Column(name = "date_time_created")
#Temporal(TemporalType.TIMESTAMP)
private Date dateTimeCreated;
#Column(name = "date_time_modified")
#Temporal(TemporalType.TIMESTAMP)
private Date dateTimeModified;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "ticketId")
private List<TicketFollower> ticketFollowerList;
#JoinColumn(name = "project_id", referencedColumnName = "id")
#ManyToOne(optional = false)
private Project projectId;
#JoinColumn(name = "ticket_attachment_id", referencedColumnName = "id")
#ManyToOne
private TicketAttachment ticketAttachmentId;
#JoinColumn(name = "user_id", referencedColumnName = "id")
#ManyToOne(optional = false)
private User userId;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "ticketId")
private List<TicketComment> ticketCommentList;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "ticketId")
private List<TicketAttachment> ticketAttachmentList;
#Inject
public Ticket() {
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
...
#Override
public String toString() {
return getTitle();
}
}
#Entity
#Table(name = "user")
#NamedQueries({
#NamedQuery(name = "User.findAll", query = "SELECT u FROM User u")})
public class User extends AbstractEntity {
#Enumerated(EnumType.STRING)
#Column(name = "role")
private Role role;
#Column(name = "username")
private String username;
#Column(name = "password")
private String password;
#Column(name = "first_name")
private String firstName;
#Column(name = "last_name")
private String lastName;
#Column(name = "email")
private String email;
#Column(name = "avatar_path")
private String avatarPath;
#Column(name = "date_time_registered")
#Temporal(TemporalType.TIMESTAMP)
private Date dateTimeRegistered;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "userId")
private List<TicketFollower> ticketFollowerList;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "userId")
private List<Ticket> ticketList;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "userId")
private List<TicketComment> ticketCommentList;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "userId")
private List<ProjectFollower> projectFollowerList;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "userId")
private List<TicketAttachment> ticketAttachmentList;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "userId")
private List<Project> projectList;
#Inject
public User() {}
public Role getRole() {
return role;
}
public void setRole(Role role) {
this.role = role;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
I get this exception from creating a hibernate Criteria. In my TicketDao class I have a method which search ticket by username, and when I invoke code below
Criteria criteria = session.createCriteria(Ticket.class);
criteria.add(Restrictions.eq("userId.username", username));
it throws exception:
could not resolve property: userId.username of: com.entities.Ticket
However, when I write criteria like:
criteria.add(Restrictions.eq("userId.id", userId));
it does not show any exception and returns me result. Any idea why my syntax for criteria.add(Restrictions.eq("userId.username", username)); and other properties like firstname, last name is wrong ?
Criteria does not work like EL or Java methods or attributes, you cannot refer to inner objects with a dot ..
You have to create a restriction in Ticket, right? What does Ticket has? An User. Then... you have to create a new User, set the username to this User and then set the created User to Ticket's criteria:
Criteria criteria = session.createCriteria(Ticket.class);
User user = new User();
user.setUsername(username);
criteria.add(Restrictions.eq("user", user));
This is most likely a very basic question, but nevertheless:
Basically the User entity has an Id and a privilege enum.
The group has an id and a name.
I wonder how to model a relationship where an user can be in multiple groups, having different privilege levels in different groups. Every group can of course have multiple members.
What's the way I'm supposed to solve that idiomatically with Hibernate?
Adding some membership field to User? A membership field to Group? Both? Creating a new class for it? Which annotations are required to wire these things together?
I used next architecture
UserEntity class
#Entity
#Table(name = "user")
public class UserEntity implements Serializable {
private Long user_id;
private String username;
private String password;
public UserEntity() {
}
public UserEntity(String name, String passwd) {
username = name;
password = passwd;
}
#Column(name = "password", nullable = false)
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#Id
#Column(name = "id")
#GeneratedValue(strategy = GenerationType.AUTO)
public Long getUser_id() {
return user_id;
}
public void setUser_id(Long user_id) {
this.user_id = user_id;
}
#Column(name = "username", nullable = false)
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
AuthorityEntity class
#Entity
#Table(name = "authority_role")
public class AuthorityEntity implements Serializable {
private Integer id;
private String authority;
private List<UserEntity> people;
public AuthorityEntity() {
}
public AuthorityEntity(String authString) {
authority = authString;
}
#Column(name = "authority", nullable = false)
public String getAuthority() {
return authority;
}
public void setAuthority(String authority) {
this.authority = authority;
}
#Id
#Column(name = "id")
#GeneratedValue(strategy = GenerationType.AUTO)
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
#ManyToMany(targetEntity = UserEntity.class,
cascade = {CascadeType.PERSIST, CascadeType.MERGE})
#JoinTable(name = "authority_role_people",
joinColumns =
#JoinColumn(name = "authority_role_id"),
inverseJoinColumns =
#JoinColumn(name = "user_id"))
public List<UserEntity> getPeople() {
return people;
}
public void setPeople(List<UserEntity> people) {
this.people = people;
}
}
In fact - this is how implemented spring security plugin.
In your case you can implement that architecture, which will be more useful for you.