简体   繁体   中英

Can Hibernate update two tables with one bean?

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", nullable = 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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM