mysql_注解的方式_序列_JPA(三):JPA基本注解

基本注解

@Entity

标注用于实体类声明语句之前,指出该Java类为实体类,将映射到指定的数据库表。如声明一个实体类Customer,将它映射到数据的coustomer表上。

packagecom.dxsoft.jpa.helloword;importjavax.persistence.Entity;

@Entitypublic classPerson {//...

}

@Table

当实体类与其映射的数据库表名不同名时,需要使用@Table标注说明,该注解与@Entity标注并列使用,置于实体类声明语句之前,可写于单独语句行,也可与声明数据同行。

@Table标注的常用选项是name,用于指明数据库的表名。

@Table标注还有两个可选项catalog和schema用于设置表所属的数据库目录或模式,通常为数据库名。

uniqueConstraints选项用于设置约束条件,通常不须设置。

packagecom.dxsoft.jpa.helloword;importjavax.persistence.Entity;importjavax.persistence.Table;

@Entity

@Table(name= "jpa_person")public classPerson {//。。。

}

@Id

@Id标注用于声明一个实体类的属性映射为数据库的主键列。该属性通常置于属性声明语句之前,可与声明数据同行,也可卸载单独行上。

@Id标注也可置于属性的getter方法之前。

@GeneratedValue

@GeneratedValue用于标注主键的生成策略,通过strategy属性指定。默认情况下,JPA自动选择一个最合适底层数据库的主键生成策略:SqlServer对应identity,MySql对饮auto increment。

在javax.persistence.GenerationType中定义了以下几种可供选择的策略:

--- IDENTITY:采用数据库ID自增长的方式来自增主键字段,Oracle不支持这种方式(oracle12g后,应该支持了。);

--- AUTO:JPA自动选择合适的策略,是默认选项;

--- SEQUENCE:通过序列产生主键,通过@SequenceGenerator注解指定序列名,MySql不支持这种方式。

--- TABLE:通过表产生键,框架借助由表模拟序列产生主键,使用该策略可以使应用更易于数据库移植。

22f9ef5253d68e1c669f31586cc95da9.png

@Column

当实体的属性与其映射的数据库表的列不同名时需要使用@Column标注说明,该属性通常置于实体的属性声明语句之前,还可与@Id标注一起使用。

@Column标注的常量属性是name,用于设置映射数据库表的列名。此外,该注解还包含其他多个属性,比如:unique,nullable,length等。

@Column标注的columnDefinition属性:表示该字段在数据中的实际类型,通常ORM框架可以根据属性类型自动判断数据中的字段的类型,但是对于Date类型仍无法确定数据库中字段类型究竟是Date,Time还是Timestamp。此外,String的默认类型为varchar,如果要将String类型映射到特定数据库的BLOB或Text字段类型。

@Column标注也可以置于属性的getter方法之前。

22d518f85caf5fa36a113591b9414fe9.png

@Basic

@Basic表示一个简单的属性到数据库表的字段的映射,对于没有任何标注的getXxx()方法,默认即为Basic

fetch:表示该属性的读取策略,有EAGER和LAZY两种,分别表示主支抓取和延迟加载,默认为EAGER

optional:表示该属性是否允许为null,默认为true。

d0db414d3247c2f3cd75c6e16670b13e.png

@Transient

表示该属性并非一个到数据库表的字段的映射,ORM框架将忽略该属性。

如果一个属性并非数据库的字段映射,就务必将其标示为@Transient,否则,ORM框架默认其注解为@Basic。

假设Person类需要扩展一个帮助方法,getUserInfo()

//帮助方法,不希望保存到数据库,但是需要动态获取Customer对象的属性。

publicString getUserInfo() {return "username:" + fullName + ",age:" +age;

}

此时,运行时抛出异常。

解决上边需求,而且又不抛异常的方案:需要在getUserInfo()方法上添加注解@Transient

b2929b7a31f9f26fb47f29bc474e37bb.png

@Temporal

在核心的JAVA API中并没有定义Date类型的精度(temporal precision)。而在数据库中,表示Date类型的数据类型有DATE,TIME和TEIMSTAMP三种精度(即单纯的日期,时间,或者两者兼备)。在运行属性映射是可使用

@Temporal注解来调整Date精度。

修改项目:

1)修改Person实体类,新增birth,createTime字段

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

packagecom.dxsoft.jpa.helloword;importjava.util.Date;importjavax.persistence.Column;importjavax.persistence.Entity;importjavax.persistence.GeneratedValue;importjavax.persistence.GenerationType;importjavax.persistence.Id;importjavax.persistence.Table;importjavax.persistence.Transient;

@Entity

@Table(name= "jpa_person")public classPerson {privateInteger id;privateString fullName;private intage;privateDate birth;privateDate createTime;publicPerson() {

}

@GeneratedValue(strategy=GenerationType.AUTO)

@IdpublicInteger getId() {returnid;

}public voidsetId(Integer id) {this.id =id;

}

@Column(name= "full_name", nullable = false, length = 64)publicString getFullName() {returnfullName;

}public voidsetFullName(String fullName) {this.fullName =fullName;

}public intgetAge() {returnage;

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

}publicDate getBirth() {returnbirth;

}public voidsetBirth(Date birth) {this.birth =birth;

}publicDate getCreateTime() {returncreateTime;

}public voidsetCreateTime(Date createTime) {this.createTime =createTime;

}//帮助方法,不希望保存到数据库,但是需要动态获取Customer对象的属性。

@TransientpublicString getUserInfo() {return "username:" + fullName + ",age:" +age;

}

@OverridepublicString toString() {return "Person [id=" + id + ", fullName=" + fullName + ", age=" + age + "]";

}

}

View Code

2)修改测试main函数

282859777c286b3fd6a9302ea95e7dac.png

此时,删除mysql数据中的jpa_person表,重新运行。

运行日志:

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

Hibernate:

create table hibernate_sequence (

next_val bigint

) engine=InnoDB

Hibernate:

insert into hibernate_sequence values (1)

Hibernate:

create table jpa_person (

id integer notnull,

age integer notnull,

birth datetime,

createTime datetime,

full_name varchar(64) not null,

primary key (id)

) engine=InnoDB

Fri Jun15 12:25:35 CST 2018 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore forserver certificate verification.

Hibernate:

select

next_val as id_val

from

hibernate_sequenceforupdate

Hibernate:

update

hibernate_sequence

set

next_val= ?where

next_val=?Hibernate:

insert

into

jpa_person

(age, birth, createTime, full_name, id)

values

(?, ?, ?, ?, ?)

六月15, 2018 12:25:35下午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop

INFO: HHH10001008: Cleaning up connection pool [jdbc:mysql://127.0.0.1:3306/jpa]

complete..

View Code

此时查看mysql中表

068fc3ac7a37dbdeef6d17482dc5c947.png

f9c554c95095bb3694a28e62c0ab9d0c.png

显然这里的createTime可以使用,但是birth的日期精度要求是短日期格式就可以。

使用@Temporal注解来调整Date精度

修改person.java实体类

b167f471421bfaaf1ec57688d479a724.png

删除mysql中数据库jpa_person表,重新运行查看数据表结构,及数据。

运行日志:

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

Hibernate:

create table hibernate_sequence (

next_val bigint

) engine=InnoDB

Hibernate:

insert into hibernate_sequence values (1)

Hibernate:

create table jpa_person (

id integer notnull,

age integer notnull,

birth date,

createTime datetime,

full_name varchar(64) not null,

primary key (id)

) engine=InnoDB

Fri Jun15 12:30:16 CST 2018 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore forserver certificate verification.

Hibernate:

select

next_val as id_val

from

hibernate_sequenceforupdate

Hibernate:

update

hibernate_sequence

set

next_val= ?where

next_val=?Hibernate:

insert

into

jpa_person

(age, birth, createTime, full_name, id)

values

(?, ?, ?, ?, ?)

六月15, 2018 12:30:16下午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop

INFO: HHH10001008: Cleaning up connection pool [jdbc:mysql://127.0.0.1:3306/jpa]

complete..

View Code

dfde4380a3070c181b8d0ac6813bb9b5.png

e17af8c3a7aef39730b555895a8d8658.png

用table来生成数据表的主键

将当前主键的值单独保存到一个数据的表中,主键的值每次都是从指定的表中查询获得

这种方式生成主键的策略可以适用于任何数据库,不必担心不同数据不兼容造成的问题。

1)修改Person.java

@TableGenerator(

name= "person_id_generator",

table= "jpa_id_generator",

pkColumnName= "pk_name",

pkColumnValue= "person_id",

valueColumnName= "pk_value",

initialValue= 1,

allocationSize= 100)

@GeneratedValue(

strategy=GenerationType.TABLE,

generator= "person_id_generator")

@IdpublicInteger getId() {returnid;

}public voidsetId(Integer id) {this.id =id;

}

2)删除已经存在表jpa_person,重新执行三次main函数:

3)发现新增了jpa_id_generator表,表jpa_id_generator中也有了记录:

jpa_person记录为:

7105a9600194140d779833e9089e4280.png

jpa_id_generator记录为:

5ccc8333e7f515fc27168b1073fa9d92.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值