Hibernate 注解方式

  1. 云栖社区>
  2. 博客>
  3. 正文

Hibernate 注解方式

gabriel丶 2018-10-29 14:34:00 浏览551
展开阅读全文

第一次接触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='黄土高坡'}

可以看到我们的设置都成功了并且也输出了魔法少女,注解配置到此结束。

网友评论

登录后评论
0/500
评论
gabriel丶
+ 关注