今天有时间大体看了一下Hibernate Annotations,决定放弃xdoclet生成hbm的想法,开始学习annotation.
首先大体的来看一下:
一:Class Level:
1:通过@Entity声明当前pojo为实体Bean
2:通过@Table定义对应数据库表的属性
name:表名,默认实体类名
uniqueConstraints:定义表的唯一性约束
例:定义表名为tb_user,并且用户名唯一,不能重复
@Entity
@Table(
name = " tb_user " ,
uniqueConstraints =
{@UniqueConstraint(columnNames = "userName")}
)
public class User implements Serializable {
private Integer id;
private String userName;
}
@Table(
name = " tb_user " ,
uniqueConstraints =
{@UniqueConstraint(columnNames = "userName")}
)
public class User implements Serializable {
private Integer id;
private String userName;
}
二:Method Level:
@Basic
@Transient
@Column
所有非static非transient都会被持久化,也就是说所有加@Transient是不会被保存到数据库中的,所有没有加注的默认为@Basic,通过Column我们可以更一步的定义列名,是否为空,长度,是否可更新等等属性值,
例:
@Column(name
=
"
userName
"
, nullable
=
false
, length
=
80
, unique
=
true
)
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
@Transient
public String getPassword() {
return password;
}
默认的列名就是属性名,上面的name="userName"只是演示而已。
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
@Transient
public String getPassword() {
return password;
}
password加注为@Transient,所以通过SchemaExport导入Schema,查看表结构是没有这个字段的。
@Temporal
日期类型,分三种,Time,Date,Timestamp
例:
@Temporal(TemporalType.TIMESTAMP)
public Date getBirthday() {
return birthday;
}
public Date getBirthday() {
return birthday;
}
@Lob
1:所有的Clob, Character,char,String都会被转为Clob
2:所有的Blob,Byte[],byte[],serializable都会被转为Blob
例:
@Lob
public Clob getResume() {
return resume;
}
@Lob
public Blob getImage() {
return image;
}
public Clob getResume() {
return resume;
}
@Lob
public Blob getImage() {
return image;
}
@Id
就是标识了,暂时还没有详读文档,看了一下test
最简单方式如下:
@Id
@GeneratedValue
public String getId() {
return id;
}
@GeneratedValue
public String getId() {
return id;
}
我看了一下mysql生成的sql
id
integer
not
null
auto_increment,
primary key (id),
primary key (id),
应该是hibernate根据数据库类型自动选择的(说了一句废话 ),我猜是生成方式native
当然我们可以根据我们需要选择其他的生成方式,例如常用的uuid
@Id
@GeneratedValue(generator = " system-uuid " )
@GenericGenerator(name = " system-uuid " , strategy = " uuid " )
public Integer getId() {
return id;
}
@GeneratedValue(generator = " system-uuid " )
@GenericGenerator(name = " system-uuid " , strategy = " uuid " )
public Integer getId() {
return id;
}
@Version
乐观锁
三:跑起来
和Hibernate官方网站一样,来个HibernateUtil
/**
* @author martin
*/
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
AnnotationConfiguration cfg =
new AnnotationConfiguration().addAnnotatedClass(User. class );
new SchemaExport(cfg).execute( true , true , false , true );
sessionFactory = cfg.buildSessionFactory();
}
public static Session getSession() {
return sessionFactory.openSession();
}
}
* @author martin
*/
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
AnnotationConfiguration cfg =
new AnnotationConfiguration().addAnnotatedClass(User. class );
new SchemaExport(cfg).execute( true , true , false , true );
sessionFactory = cfg.buildSessionFactory();
}
public static Session getSession() {
return sessionFactory.openSession();
}
}
注意这里的 new AnnotationConfiguration()!
Test:
/**
* @author martin
*/
public class HibernateUtilTest extends TestCase {
public void testAddUser() {
User user = new User();
user.setUserName( " martin " );
save(user);
assertNotNull(user.getId());
}
public void testUpdateUser() {
Session session = HibernateUtil.getSession();
Query query =
session.createQuery( " from User as user where user.userName=:name " );
query.setParameter( " name " , " martin " );
List list = query.list();
session.close();
assertEquals( 1 , list.size());
User user = (User) list.get( 0 );
user.setUserName( " martin xus " );
save(user);
assertEquals( new Integer( 1 ), user.getVersion());
}
private void save(User user) {
Session session = HibernateUtil.getSession();
Transaction tx = session.beginTransaction();
session.saveOrUpdate(user);
session.flush();
tx.commit();
session.close();
}
}
* @author martin
*/
public class HibernateUtilTest extends TestCase {
public void testAddUser() {
User user = new User();
user.setUserName( " martin " );
save(user);
assertNotNull(user.getId());
}
public void testUpdateUser() {
Session session = HibernateUtil.getSession();
Query query =
session.createQuery( " from User as user where user.userName=:name " );
query.setParameter( " name " , " martin " );
List list = query.list();
session.close();
assertEquals( 1 , list.size());
User user = (User) list.get( 0 );
user.setUserName( " martin xus " );
save(user);
assertEquals( new Integer( 1 ), user.getVersion());
}
private void save(User user) {
Session session = HibernateUtil.getSession();
Transaction tx = session.beginTransaction();
session.saveOrUpdate(user);
session.flush();
tx.commit();
session.close();
}
}
创建的表结构为:
create
table
tb_user (
id varchar ( 32 ) not null ,
birthday datetime ,
resume text ,
image blob,
optlock integer ,
password varchar ( 255 ),
userName varchar ( 80 ) not null unique ,
primary key (id),
unique (userName)
)
id varchar ( 32 ) not null ,
birthday datetime ,
resume text ,
image blob,
optlock integer ,
password varchar ( 255 ),
userName varchar ( 80 ) not null unique ,
primary key (id),
unique (userName)
)
完整User代码(省掉了所有属性的setter):
import
org.hibernate.annotations.GenericGenerator;
import javax.persistence. * ;
import java.io.Serializable;
import java.util.Date;
import java.sql.Clob;
import java.sql.Blob;
/**
* @author martin
*/
@Entity
@Table(
name = " tb_user " ,
uniqueConstraints =
{@UniqueConstraint(columnNames = "userName")}
)
public class User implements Serializable {
private String id;
private String userName;
private String password;
private Date birthday;
private Clob resume;
private Blob image;
private Integer version;
@Id
@GeneratedValue(generator = "system-uuid")
@GenericGenerator(name = "system-uuid", strategy = "uuid")
@Column(length = 32)
public String getId() {
return id;
}
@Column(nullable = false, length = 80, unique = true)
public String getUserName() {
return userName;
}
public String getPassword() {
return password;
}
@Temporal(TemporalType.TIMESTAMP)
public Date getBirthday() {
return birthday;
}
@Version
@Column(name = "optlock")
public Integer getVersion() {
return version;
}
@Lob
public Clob getResume() {
return resume;
}
@Lob
public Blob getImage() {
return image;
}
//setter
}
import javax.persistence. * ;
import java.io.Serializable;
import java.util.Date;
import java.sql.Clob;
import java.sql.Blob;
/**
* @author martin
*/
@Entity
@Table(
name = " tb_user " ,
uniqueConstraints =
{@UniqueConstraint(columnNames = "userName")}
)
public class User implements Serializable {
private String id;
private String userName;
private String password;
private Date birthday;
private Clob resume;
private Blob image;
private Integer version;
@Id
@GeneratedValue(generator = "system-uuid")
@GenericGenerator(name = "system-uuid", strategy = "uuid")
@Column(length = 32)
public String getId() {
return id;
}
@Column(nullable = false, length = 80, unique = true)
public String getUserName() {
return userName;
}
public String getPassword() {
return password;
}
@Temporal(TemporalType.TIMESTAMP)
public Date getBirthday() {
return birthday;
}
@Version
@Column(name = "optlock")
public Integer getVersion() {
return version;
}
@Lob
public Clob getResume() {
return resume;
}
@Lob
public Blob getImage() {
return image;
}
//setter
}
四:next,明天的学习计划.
参考
Hibernate Annotations Refrence