I am working on a project using Hibernate and Spring; single screen, one bean, but two tables. I wanted to know if Hibernate can update two MySQL tables within a single call?
If so, how do I code the following bean (model) to update two tables!
User name and password is in the user table. User name and enabled is in the rights table.
Below is my code:
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue
@Column(name = "userid")
private Long userId; // in user and rights tables!
@NotEmpty(message = "User name must not be blank.")
@Size(max = 20)
@Column(name = "username", nullable = false, length = 20)
private String username; // in user table
@NotEmpty(message = "Password must not be blank.")
@Size(max = 20)
@Column(name = "password", nullab开发者_如何学JAVAle = false)
private String password; // in user table
@Column(name = "enabled")
private Long enabled; // in rights table
}
You'll need to use a @SecondaryTable annotation and specify the name of that table in appropriate @Column annotations:
@Entity
@Table(name="users")
@SecondaryTable(name="rights", pkJoinColumns=
@PrimaryKeyJoinColumn(name="userid", referencedColumnName="userid")
)
public class User {
...
@Column(name = "enabled", table="rights")
private Long enabled; // in rights table
I'm pretty sure you cannot do this. In some sense, ORM is about mapping one row to one object. The best you can do is use a SQL view to create a read-only structure corresponding to this bean. That would allow you to query your data into the structure you've devised, but you would not be able to do updates.
IF you require it to be in a different table, do something like this
class User {
Long userid;
String username; // why both a userid and a username?
String password;
Rights rights;
}
class Rights {
boolean enabled;
boolean canModerate;
int maxSomething;
// other rights here
}
精彩评论