【Hibernate】Re03 注解方式实现

使用JPA规范提供的注解即可实现,这样的好处是不需要配置Entity.hbm.xml文件了

但是考虑到多表查询的情况,还是会有xml配置的需要。

一、常用的JPA注解:

1、public @interface javax.persistence.Entity 
注解的类声明为持久化类

2、public @interface javax.persistence.Table 
为持久化类指定数据表名称(table),默认值是首字母小写的类名
目录名称(catalog)
和约束名称(schema)

3、public @interface javax.persistence.Id
声明持久化类的标识属性,OID,也就是主键

4、public @interface javax.persistence.GeneratedValue
定义标识属性值的生成策略

5、public @interface javax.persistence.UniqueConstraint
表的唯一约束

6、public @interface javax.persistence.Lob
注解的属性持久化为Blob或者Clob类型

7、public @interface javax.persistence.Column
属性映射到数据库字段,指定name值为表字段名称

8、public @interface javax.persistence.Transient 
指定非持久化的字段属性

创建User实体类:

官方的实例中是把注解打在GETTER方法上的,和之前的视频教程并不一样

package cn.zeal4j.domain;

/**
 * @author Administrator
 * @file Hibernate
 * @create 2020 09 23 22:09
 */

import org.hibernate.annotations.GenericGenerator;

import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;

@Entity
@Table(name = "user")  // name属性值会报错,不用担心
public class User implements Serializable {
    private Integer id;
    private String username;
    private String password;
    private Date reg_time;

    public User() {
    }

    public User(Integer id, String username, String password) {
        this.id = id;
        this.username = username;
        this.password = password;
    }

    public User(Integer id, String username, String password, Date reg_time) {
        this(id, username, password);
        this.reg_time = reg_time;
    }

    @Id // 该注解定义实体标识符的属性
    @GeneratedValue(generator = "increment", strategy = GenerationType.AUTO) // 两个主键生成策略,指示Hibernate如何生成
    @GenericGenerator(name = "increment", strategy = "increment")
    public Integer getId() {
        return id;
    }

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

    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;
    }

    @Temporal(TemporalType.DATE) // 可以对时间类型的数据注解JPA提供的枚举时间类型     DATE,     TIME,     TIMESTAMP;
    @Column(name = "reg_time") // 标注类属性对应的表字段名称
    public Date getReg_time() {
        return reg_time;
    }

    public void setReg_time(Date reg_time) {
        this.reg_time = reg_time;
    }

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

当然Hibernate核心配置文件还是需要编写的

映射配置标签改为class设置即可:

<?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://IP-Address:Port/hibernate?serverTimezone=Asia/Shanghai</property>
        <property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
        <property name="connection.username">Username</property>
        <property name="connection.password">Password</property>

        <property name="dialect">org.hibernate.dialect.MySQL57Dialect</property> <!-- 数据库版本方言 -->
        <property name="show_sql">true</property> <!-- 是否让控制台输出SQL语句 -->
        <property name="format_sql">true</property> <!-- 控制台输出的SQL格式化 -->
        <property name="hbm2ddl.auto">update</property> <!-- 数据库表的生成策略 -->

        <mapping resource="hibernate/mapping/News.hbm.xml" /> <!-- 实体类映射XML路径 -->
        <mapping class="cn.zeal4j.domain.User" /> <!-- 使用注解的配置方式 --> 
    </session-factory>

</hibernate-configuration>

打印输出:

Hibernate: 
    
    create table user (
       id integer not null,
        password varchar(255),
        reg_time date,
        username varchar(255),
        primary key (id)
    ) engine=InnoDB
九月 23, 2020 10:32:18 下午 org.hibernate.engine.transaction.jta.platform.internal.JtaPlatformInitiator initiateService
INFO: HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
Hibernate: 
    select
        max(id) 
    from
        user
user id  -> 1
Hibernate: 
    insert 
    into
        user
        (password, reg_time, username, id) 
    values
        (?, ?, ?, ?)

查看数据库:

二、关联关系注解:

发现了Lombok堆溢出的错误是由@Data注解造成的,改用@Setter @Getter注解则不会报错

实体类A

package cn.zeal4j.domain;

import lombok.*;
import org.hibernate.annotations.GenericGenerator;

import javax.persistence.*;
import java.io.Serializable;

/**
 * @author Administrator
 * @file Hibernate-Tutorial
 * @create 2020 09 27 10:13
 */
@Entity
@Table(name = "a")
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
public class EntityA implements Serializable {
    private static final long serialVersionUID = -2888634867818013382L;
    @Id
    @GeneratedValue(generator = "increment", strategy = GenerationType.AUTO)
    @GenericGenerator(name = "increment", strategy = "increment")
    private Integer id;
    private String info;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "b_id")
    private EntityB entityB;
}

实体类B

package cn.zeal4j.domain;

import lombok.*;
import org.hibernate.annotations.GenericGenerator;

import javax.persistence.*;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;

/**
 * @author Administrator
 * @file Hibernate-Tutorial
 * @create 2020 09 27 10:13
 */
@Entity
@Table(name = "b")
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
public class EntityB implements Serializable {
    private static final long serialVersionUID = -1308014214512822794L;
    @Id
    @GeneratedValue(generator = "increment", strategy = GenerationType.AUTO)
    @GenericGenerator(name = "increment", strategy = "increment")
    private Integer id;
    private String info;

    @OneToMany(mappedBy = "entityB", cascade = {CascadeType.ALL})
    private Set<EntityA> entityASet = new HashSet<>();
}

执行的SQL语句

Hibernate: 
    
    create table a (
       id integer not null,
        info varchar(255),
        b_id integer,
        primary key (id)
    ) engine=InnoDB
Hibernate: 
    
    create table b (
       id integer not null,
        info varchar(255),
        primary key (id)
    ) engine=InnoDB
Hibernate: 
    
    alter table a 
       add constraint FKh2icx52jhor7siuxpgqqki6bi 
       foreign key (b_id) 
       references b (id)
九月 27, 2020 10:34:40 上午 org.hibernate.engine.transaction.jta.platform.internal.JtaPlatformInitiator initiateService
INFO: HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
Hibernate: 
    select
        max(id) 
    from
        b
Hibernate: 
    select
        max(id) 
    from
        a
Hibernate: 
    insert 
    into
        b
        (info, id) 
    values
        (?, ?)
Hibernate: 
    insert 
    into
        a
        (b_id, info, id) 
    values
        (?, ?, ?)

Process finished with exit code 0

 

posted @ 2020-09-23 22:35  emdzz  阅读(940)  评论(0编辑  收藏  举报