简体   繁体   中英

How to create classes with hibernate annotations for specific SQL query

I'm currently working on a login/registration service for my website. Can somebody explain to me how java classes for the query posted below should look like?

CREATE TABLE users 
(
    username VARCHAR(50) NOT NULL,
    password VARCHAR(100) NOT NULL,
    enabled TINYINT NOT NULL DEFAULT 1,
    PRIMARY KEY (username)
);
  
CREATE TABLE authorities 
(
    username VARCHAR(50) NOT NULL,
    authority VARCHAR(50) NOT NULL,
    FOREIGN KEY (username) REFERENCES users(username)
);
 
CREATE UNIQUE INDEX ix_auth_username
  ON authorities (username, authority);

I have a problem with hibernate annotations. Don't know how to correctly join the "authority" column.

I've created these two classes shown below:

Users.java

@Entity
public class Users extends AbstractEntity implements Cloneable {

    @NotNull
    @NotEmpty
    private String username = "";

    @NotNull
    @NotEmpty
    private String password = "";

    @NotNull
    @ColumnDefault(value = "1")
    private byte enabled;

    //here is the problem
    @OneToMany
    @JoinColumn(name = "authorities_username")
    private Authorities authorities;

    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 byte getEnabled() {
        return enabled;
    }

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

    public Authorities getAuthorities() {
        return authorities;
    }

    public void setAuthorities(Authorities authorities) {
        this.authorities = authorities;
    }
}

Authorities.java

@Entity
public class Authorities extends AbstractEntity{
    private String username;

    public enum Authority {
        ROLE_USER, ROLE_ADMIN
    }

    @NotNull
    @Enumerated(EnumType.STRING)
    @OneToMany
    private Authorities.Authority authority;

    public Authorities() { }

    public String getUsername() {
        return username;
    }

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

    public Authority getAuthority() {
        return authority;
    }
}

PS. Sorry for my English ;)

AbstractEntity.java

@MappedSuperclass
public abstract class AbstractEntity {
    @Id
    @GeneratedValue(strategy= GenerationType.SEQUENCE)
    private Long id;

    public Long getId() {
        return id;
    }

    public boolean isPersisted() {
        return id != null;
    }

    @Override
    public int hashCode() {
        if (getId() != null) {
            return getId().hashCode();
        }
        return super.hashCode();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        AbstractEntity other = (AbstractEntity) obj;
        if (getId() == null || other.getId() == null) {
            return false;
        }
        return getId().equals(other.getId());
    }
}

I think you need to use @OneToMany(mappedBy="authorities") annotation in your Authorities class.

Also see: https://en.wikibooks.org/wiki/Java_Persistence/ManyToOne

Hope that helps. All the best.

if your problem with mapping enum filed you can do it like this :

    @Column(name="myenum") 
    @Enumerated(EnumType.ORDINAL) 
    private MyEnum myEnum;

You can specify how the enum should be persisted in the database with the EnumType enum property of the @Enumerated annotation. EnumType.ORDINAL specifies that the enum will be persisted as an integer value. Here, MyEnum set to VALUE1 would be persisted as 0, VALUE2 as 1, etc.

The alternative is to use EnumType.STRING to specify that the enum will be persisted using the name of the enum value that the field is set to. So, applied to the previous example, setting the field Myenum to MyEnum.VALUE1 will persist as VALUE1, etc.

first of all, dont forget that define your enum like this in another .java file :

public enum myEnum {
    value1(0, "value1");
    }

You can use the hiberante tools. Run mvn org.hibernate:hibernate-tools-maven-plugin:hbm2java in directory wiht pom.exe with

<plugin>
       <groupId>org.hibernate</groupId>
       <artifactId>hibernate-tools-maven-plugin</artifactId>
       <version>5.4.19.Final</version>
       <executions>
             <execution>
                    <id>Display Help</id>
                    <phase>validate</phase>
                    <goals>
                           <goal>help</goal>
                    </goals>
             </execution>
             <execution>
                    <id>Entity generation</id>
                    <phase>validate</phase>
                    <goals>
                           <goal>hbm2java</goal>
                    </goals>
             </execution>
       </executions>
       <configuration>
             <revengFile>${project.basedir}/src/assembly/hibernate.reveng.xml</revengFile>
             <packageName>[your packageName]</packageName>
             <detectManyToMany>true</detectManyToMany>
             <detectOneToOne>true</detectOneToOne>
             <detectOptimisticLock>true</detectOptimisticLock>
             <createCollectionForForeignKey>true</createCollectionForForeignKey>
             <createManyToOneForForeignKey>true</createManyToOneForForeignKey>
             <outputDirectory>${project.basedir}/src/main/java</outputDirectory>
             <ejb3>true</ejb3>
             <jdk5>true</jdk5>
       </configuration>
       <dependencies>
             <dependency>
                    <groupId>org.postgresql</groupId>
                    <artifactId>postgresql</artifactId>
                    <version>${postgresqlVersion}</version>
             </dependency>
       </dependencies>
</plugin>

and hibernate-tools will generate an entities with annotations

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