Hibernate 註解方式

weixin_34195546發表於2018-10-29

第一次接觸HIbernate都是以XML方式,今天來看看註解的方式如何寫

1. hibernate的常用註解

//標識實體類
@Entity 
//該實體類對應的表 預設對應的表為類名 可通過@Table(name ="xxx")來標識實體類名與表名不同的情況
@Table 
//實體類的標識屬性
@Id
//主鍵的生成策略
//strategy 生產策略有以下值
//GenerationType.AUTO 由程式控制 預設值
//GenerationType.IDENTITY 由資料庫生成
//GenerationType.SEQUENCE 由序列生成 需要資料庫支援
@GeneratedValue 
//屬性對應的列 可通過@Column(name="xxx")來標識屬性和列名不同的情況
@Column 
//設定一對一關聯
@OneToOne
//設定一對多關聯
@OneToMany
//設定多對一關聯
@ManyToOne
//設定多對多關聯
@ManyToMany
//設定外來鍵
@JoinColumn
//設定關聯表
@JoinTable

接下來寫一個簡單使用者類

2. User類

package pojo;

import javax.persistence.*;

/**
 * Created by Administrator on 2018/10/29.
 */
@Entity
@Table(name = "customer")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    @Column(name="uname",length = 255,nullable = false,unique = true)
    private String username;

    @Column(name="name",length = 255)
    private String nickname;

    @Column(name="pword",length = 255,nullable = false)
    private String password;

    @Column(name = "age",nullable = false)
    private int age;

    @Column(name="address",unique = true)
    private String address;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

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

    public String getNickname() {
        return nickname;
    }

    public void setNickname(String nickname) {
        this.nickname = nickname;
    }

    public String getPassword() {
        return password;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", nickname='" + nickname + '\'' +
                ", password='" + password + '\'' +
                ", age=" + age +
                ", address='" + address + '\'' +
                '}';
    }
}

3. hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <!-- 資料來源設定 -->
        <property name="connection.url" >jdbc:mysql:///test</property>
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.username">root</property>
        <property name="connection.password">root</property>

        <!-- hibernate設定 -->
        <property name="hbm2ddl.auto">update</property>
        <property name="show_sql">true</property>
        <property name="format_sql">true</property>

        <!-- xml方式 屬性使用resource -->
        <!-- 註解方式 屬性使用class -->
        <mapping class="pojo.User"/>
    </session-factory>
</hibernate-configuration>

4. 測試

Main.java

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import pojo.User;

/**
 * Created by Administrator on 2018/10/29.
 */
public class Main {
    private static final SessionFactory ourSessionFactory;

    static {
        try {
            Configuration configuration = new Configuration();
            configuration.configure();

            ourSessionFactory = configuration.buildSessionFactory();
        } catch (Throwable ex) {
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static Session getSession() throws HibernateException {
        return ourSessionFactory.openSession();
    }

    public static void main(final String[] args) throws Exception {
        final Session session = getSession();
        Transaction tx = session.beginTransaction();
        User user = new User();
        user.setUsername("mfsvejt");
        user.setNickname("魔法少女厄加特");
        user.setPassword("123456");
        user.setAge(18);
        user.setAddress("黃土高坡");

        session.save(user);
        tx.commit();

        session.createQuery("from User").list().forEach(u -> System.out.println(u));
    }
}

控制檯輸出

Hibernate: 
    
    create table customer (
       id integer not null auto_increment,
        address varchar(255),
        age integer not null,
        name varchar(255),
        pword varchar(255) not null,
        uname varchar(255) not null,
        primary key (id)
    ) engine=InnoDB
Hibernate: 
    
    alter table customer 
       drop index UK_i0stw68u1778vsgy4idl3m183
Hibernate: 
    
    alter table customer 
       add constraint UK_i0stw68u1778vsgy4idl3m183 unique (address)
Hibernate: 
    
    alter table customer 
       drop index UK_dyi49bfteml6qub2etkw376y9
Hibernate: 
    
    alter table customer 
       add constraint UK_dyi49bfteml6qub2etkw376y9 unique (uname)
Hibernate: 
    insert 
    into
        customer
        (address, age, name, pword, uname) 
    values
        (?, ?, ?, ?, ?)
十月 29, 2018 2:32:19 下午 org.hibernate.hql.internal.QueryTranslatorFactoryInitiator initiateService
INFO: HHH000397: Using ASTQueryTranslatorFactory
Hibernate: 
    select
        user0_.id as id1_0_,
        user0_.address as address2_0_,
        user0_.age as age3_0_,
        user0_.name as name4_0_,
        user0_.pword as pword5_0_,
        user0_.uname as uname6_0_ 
    from
        customer user0_
User{id=1, username='mfsvejt', nickname='魔法少女厄加特', password='123456', age=18, address='黃土高坡'}

可以看到我們的設定都成功了並且也輸出了魔法少女,註解配置到此結束。

相關文章