1. 准备工作
下载hibernate3.jar, hibernate-commons-annotations-3.3.0.ga.jar ......等jar文件
antlr-2.7.6.jar
commons-collections-3.1.jar
commons-logging.jar
dom4j-1.6.1.jar
ejb3-persistence-3.3.2.Beta1.jar
hibernate3.jar
hibernate-annotations-3.0beta2.jar
hibernate-commons-annotations-3.3.0.ga.jar
hibernate-jpa-2.0-api-1.0.0.Final.jar
hibernate-testing.jar
javassist-3.12.0.GA.jar
jta-1.1.jar
log4j.jar
ojdbc6.jar
slf4j-api-1.6.1.jar
slf4j-log4j12-1.6.1.jar
slf4j-nop-1.6.1.jar
slf4j-simple-1.6.1.jar
2. Create java project and import the jar files.
3. Create User PO class
package com.dextrys.pg.model;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.HashSet;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.GenerationType;
import javax.persistence.SequenceGenerator;
import javax.persistence.OneToMany;
import javax.persistence.ManyToMany;
import javax.persistence.CascadeType;
import javax.persistence.OrderBy;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.NamedQuery;
import org.hibernate.annotations.Formula;
@Entity
@Table( name = "USERS" )
@NamedQuery(name="user.event", query="select new map(u as user,event as events) from User u left join u.events event fetch all properties ")
public class User {
private Long id;
private String userName;
private String PASSWORD;
private Set<Event> events;
private Set<Role> role = new HashSet<Role>() ;
/*
private int count;
@Formula("(select COUNT(*) from users)")
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
*/
@OneToMany (cascade = CascadeType.REFRESH)
@JoinColumn(name="LASTUPDATEUSER",referencedColumnName="USER_ID")
public Set<Event> getEvents() {
return events;
}
public void setEvents(Set<Event> events) {
this.events = events;
}
@ManyToMany(cascade =CascadeType.PERSIST)
/**
* 多对多映射:注解@ManyToMany(单向)
* 默认情况下,hibernate会自动的创建一张中间表,
* 来维护多对多关系
* 默认中间表的名称 :user_role中间表,字段的名称user_id role_id
* 如果想更换表名和字段名称,注解如下:
*/
@JoinTable(name="T_ROLE_USER",
joinColumns={@JoinColumn(name="USER_ID")},
inverseJoinColumns={@JoinColumn(name="ROLE_ID")})
public Set<Role> getRole() {
return role;
}
public void setRole(Set<Role> role) {
this.role = role;
}
public User(){}
public User(Long id, String userName, String pASSWORD) {
super();
this.id = id;
this.userName = userName;
PASSWORD = pASSWORD;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPASSWORD() {
return PASSWORD;
}
public void setPASSWORD(String pASSWORD) {
PASSWORD = pASSWORD;
}
@Id
@Column(name = "USER_ID")
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="ET_USER_SEQ")
@SequenceGenerator(name="ET_USER_SEQ",allocationSize=1,initialValue=1, sequenceName="ET_USER_SEQ")
public Long getId() {
return id;
}
private void setId(Long id) {
this.id = id;
}
}
4. Create hibernate.cfg.xml under src folder
这里映射的是PO class, 不是xml配置文件名
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="connection.url">jdbc:oracle:thin:@10.0.2.56:1521:igcs</property>
<property name="connection.username">ACEGI</property>
<property name="connection.password">ACEGI</property>
<property name="dialect">org.hibernate.dialect.Oracle9iDialect</property>
<!-- 在控制台打印SQL语句 -->
<property name="show_sql">true</property>
<!-- 自动把实体类与属性映射成数据库中的表与列 -->
<property name="hbm2ddl.auto">update</property>
<mapping class="com.dextrys.pg.model.User"/>
</session-factory>
</hibernate-configuration>
5. Create DAO
组织关系连接
5.1 common DAO
5.2 Model DAO
public class UserDAO extends BaseDao{
private Logger logger = Logger.getLogger(this.getClass());
String databeaseError="databease Error";
public Iterator searchUser(String name){
Session session = this.getSession();
Iterator users = null;
try{
session.beginTransaction().begin();
Query q = session.getNamedQuery("user.event");
//q.setParameter(0, name);
users = q.iterate();
session.beginTransaction().commit();
}catch(Exception e) {
System.out.println(e.toString());
logger.debug(databeaseError, e);
throw new DaoException(databeaseError);
} finally {
this.closeSession(session);
}
return users;
}
/**
* Search by like
* @param name
* @return
*/
public List criteriaUser(String name){
Session session = this.getSession();
List users = null;
try{
session.beginTransaction().begin();
users = session.createCriteria(User.class)
.add( Restrictions.like("userName", name,MatchMode.ANYWHERE) ).list();
session.beginTransaction().commit();
}catch(Exception e) {
System.out.println(e.toString());
logger.debug(databeaseError, e);
throw new DaoException(databeaseError);
} finally {
this.closeSession(session);
}
return users;
}
/**
* Search by object
* @param user
* @return
*/
public List criteriaUser(User user){
Session session = this.getSession();
List users = null;
try{
session.beginTransaction().begin();
users = session.createCriteria(User.class)
.add( Example.create(user).enableLike(MatchMode.ANYWHERE) ).list();
session.beginTransaction().commit();
}catch(Exception e) {
System.out.println(e.toString());
logger.debug(databeaseError, e);
throw new DaoException(databeaseError);
} finally {
this.closeSession(session);
}
return users;
}
}
6. Create AnnotationsIllustrationTest test class
public class AnnotationsIllustrationTest extends TestCase {
private UserDAO userDao;
private Session session;
@Override
protected void setUp() throws Exception {
userDao=new UserDAO();
session = userDao.getSession();
}
@Override
protected void tearDown() throws Exception {
userDao.closeHibernateSession(session);
}
@SuppressWarnings({ "unchecked" })
public void testSave() {
Set<Role> roles = new HashSet<Role>() ;
User user = (User)userDao.getByPk(User.class, 1l);
Role role1 = new Role("R3","R3");
Role role2 = new Role("R4","R4");
roles.add(role1);
roles.add(role2);
user.setRole(roles);
userDao.saveUserRole(user);
}
@SuppressWarnings({ "unchecked" })
public void testMany2Many() {
List<User> users = userDao.find("from User u where u.id =1 ");
for(User user:users){
System.out.println("........."+user.getUserName());
Set<Role> roles=user.getRole();
for(Role role:roles)
System.out.println(role.getRoleName());
}
}
@SuppressWarnings({ "unchecked" })
public void testQueryPara() {
Iterator its=userDao.searchUser("scott");
User user=null;
while(its.hasNext()){
Map map=(Map)its.next();
user=(User)map.get("user");
System.out.println("=="+user.getUserName());
System.out.println("=="+((Set)map.get("events")).size());
}
}
}