如何为具有外键和组合键的两个表编写实体

时间:2017-07-07 06:22:19

标签: java spring-data-jpa

37.1 User Schema显示两个表:

CREATE TABLE `authorities` (
  `username` varchar(50) NOT NULL,
  `authority` varchar(50) NOT NULL,
  UNIQUE KEY `ix_auth_username` (`username`,`authority`),
  CONSTRAINT `fk_authorities_users` FOREIGN KEY (`username`) REFERENCES `users` (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


CREATE TABLE `users` (
  `username` varchar(50) NOT NULL,
  `password` varchar(50) NOT NULL,
  `enabled` tinyint(1) NOT NULL,
  PRIMARY KEY (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

如何编写实体类,以便Spring启动应用程序生成如上所示的表(实体描述与mysql架构相同)? 我也尝试使用生成的实体,但是Authorities.java没有主键,并且在添加Long类型的id作为其键后,它会抛出org.hibernate.MappingException: Could not determine type for: com.example.spring.security.acl.Users, at table: authorities, for columns: [org.hibernate.mapping.Column(users_by_username)]

Users.java:

@Entity
public class Users {
    private String username;
    private String password;
    private Byte enabled;
    private Collection<Authorities> authoritiesByUsername;

    @Id
    @Column(name = "username", nullable = false, length = 50)
    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    @Basic
    @Column(name = "password", nullable = false, length = 50)
    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Basic
    @Column(name = "enabled", nullable = false)
    public Byte getEnabled() {
        return enabled;
    }

    public void setEnabled(Byte enabled) {
        this.enabled = enabled;
    }

    @OneToMany(mappedBy = "usersByUsername")
    public Collection<Authorities> getAuthoritiesByUsername() {
        return authoritiesByUsername;
    }

    public void setAuthoritiesByUsername(Collection<Authorities> authoritiesByUsername) {
        this.authoritiesByUsername = authoritiesByUsername;
    }
}

Authorities.java:

@Entity
public class Authorities {

    private String authority;

    private Users usersByUsername;

    @Basic
    @Column(name = "authority", nullable = false, length = 50)
    public String getAuthority() {
        return authority;
    }

    public void setAuthority(String authority) {
        this.authority = authority;
    }

    @ManyToOne
    @JoinColumn(name = "username", referencedColumnName = "username", nullable = false)
    public Users getUsersByUsername() {
        return usersByUsername;
    }

    public void setUsersByUsername(Users usersByUsername) {
        this.usersByUsername = usersByUsername;
    }

0 个答案:

没有答案