20160506-hibernate入门
HQL和Criteria
HQL(Hibernate Query Language)
面向对象的查询语言,与SQL不同,HQL中的对象名是区分大小写的(除了JAVA类和属性其他部分不区分大小写);HQL中查的是对象而不是和表,并且支持多态;HQL主要通过Query来操作,Query的创建方式:
Query q = session.createQuery(hql);
from Person
from User user where user.name=:name
from User user where user.name=:name and user.birthday < :birthday
示例代码:
public static void query(String name){ Session s=null; try{ s=HibernateUntils.getSession(); String hql="from User as user where user.username=?";//from Object,查找的是对象 Query query=s.createQuery(hql); query.setString(0, name); List<User> list=query.list(); for(User user:list){ System.out.println(user.getBirthday()); } }finally{ if(s!=null){ s.close(); } } }
/** * 确定查询结果只有一条时 * @param name */ public static void uniqueQuery(String name){ Session s=null; try{ s=HibernateUntils.getSession(); String hql="from User as user where user.username=?";//from Object,查找的是对象 Query query=s.createQuery(hql); query.setString(0, name); User u=(User) query.uniqueResult(); System.out.println(u.getBirthday()); }finally{ if(s!=null){ s.close(); } } }
/** * 分页查询 * @param name */ public static void queryPage(String name){ Session s=null; try{ s=HibernateUntils.getSession(); String hql="from User as user where user.username=:name";//from Object,查找的是对象 Query query=s.createQuery(hql); query.setString("name", name); query.setFirstResult(0);//第一条记录从哪一条开始去 query.setMaxResults(10);//取多少条 List<User> list=query.list(); for(User user:list){ System.out.println(user.getBirthday()); } }finally{ if(s!=null){ s.close(); } } }
Criteria
Criteria是一种比HQL更面向对象的查询方式;Criteria的创建方式:
Criteria crit = session.createCriteria(DomainClass.class);
简单属性条件如:criteria.add(Restrictions.eq(propertyName, value)),
criteria.add(Restrictions.eqProperty(propertyName,otherPropertyName))
/** * 条件查询 * @param name */ public static void cri(String name){ Session s=null; try{ s=HibernateUntils.getSession(); Criteria c=s.createCriteria(User.class); c.add(Restrictions.eq("username", name));//加入约束条件 List<User> list=c.list(); for(User user:list){ System.out.println(user.getBirthday()); } }finally{ if(s!=null){ s.close(); } } }
小练习:
实验步骤:
1.设计domain对象User。
2.设计UserDao接口。
3.加入hibernate.jar和其依赖的包。
4.编写User.hbm.xml映射文件,可以基于hibernate/eg目录下的org/hibernate/auction/User.hbm.xml修改。
5.编写hibernate.cfg.xml配置文件,可以基于hibernate/etc/hibernate.cfg.xml修改;必须提供的几个参数:
connection.driver_class、connection.url、connection.username、connection.password、dialect、hbm2ddl.auto。
6.编写HibernateUtils类,主要用来完成Hibnerate初始化和提供一个获得Session的方法;这步可选。
7.实现UserDao接口。
源代码:
User.java 实体类
package com.dzq.domain; import java.io.Serializable; import java.util.Date; public class User implements Serializable{ private int id; private String username; private String password; private String mobile; private Date regdate; 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 getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } public Date getRegdate() { return regdate; } public void setRegdate(Date regdate) { this.regdate = regdate; } }
UserDao.java 接口
package com.dzq.dao; import com.dzq.domain.User; public interface UserDao { /** * 添加用户 * * @param user */ void addUser(User user); /** * 修改用户 * * @param user */ void updateUser(User user); /** * 删除用户 * * @param user */ void deleteUser(User user); /** * 根据id查找用户 * * @param id */ User findUserByID(int id); /** * 根据id删除用户 * * @param id */ void deleteUserByID(int id); /** * 根据用户名查找用户 * @param username */ User findUserByUN(String username); }
User.hbm.xml 实体配置
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.dzq.domain"> <class name="User" table="user"> <id name="id" column="id"> <generator class="native" /> </id> <property name="username" column="username" /> <property name="password" column="password" /> <property name="mobile" column="mobile" /> <property name="regdate" column="regdate"/> </class> </hibernate-mapping>
hibernate.cfg.xml 全局配置文件
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql:///test1</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password"></property> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <property name="hibernate.show_sql">true</property> <mapping resource="com/dzq/domain/User.hbm.xml"/> </session-factory> </hibernate-configuration>
HibernateUtils.java 工具类
package com.dzq.utils; import java.io.Serializable; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; public class HibernateUntils { private static SessionFactory sessionFactory; private HibernateUntils() { } static { Configuration cfg = new Configuration(); cfg.configure();//如果不是hibernate.cfg.xml这个文件名,需要加上文件名 sessionFactory = cfg.buildSessionFactory(); } public static SessionFactory getSessionFactory(){ return sessionFactory; } public static Session getSession(){ return sessionFactory.openSession(); } /** * 添加 * @param entity */ public static void add(Object entity) { Session s = null; Transaction tx = null; try { s = HibernateUntils.getSession(); tx = s.beginTransaction(); s.save(entity); tx.commit(); } catch (Exception e) { if (tx != null) tx.rollback(); throw new RuntimeException(e); } finally { if (s != null) { s.close(); } } } /** * 修改 * @param entity */ public static void update(Object entity) { Session s = null; Transaction tx = null; try { s = HibernateUntils.getSession(); tx = s.beginTransaction(); s.update(entity); tx.commit(); } catch (Exception e) { if (tx != null) tx.rollback(); throw new RuntimeException(e); } finally { if (s != null) { s.close(); } } } /** * 删除 * @param entity */ public static void delete(Object entity) { Session s = null; Transaction tx = null; try { s = HibernateUntils.getSession(); tx = s.beginTransaction(); s.delete(entity); tx.commit(); } catch (Exception e) { if (tx != null) tx.rollback(); throw new RuntimeException(e); } finally { if (s != null) { s.close(); } } } /** * 根据主键id查询 * @param clazz * @param id * @return */ public static Object get(Class clazz,Serializable id) { Session s = null; try { s = HibernateUntils.getSession(); Object obj=s.get(clazz, id); return obj; } finally { if (s != null) { s.close(); } } } }
UserDaoImpl.java 接口实现
package com.dzq.dao.impl; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.Transaction; import com.dzq.dao.UserDao; import com.dzq.domain.User; import com.dzq.utils.HibernateUntils; public class UserDaoImpl implements UserDao { @Override public void addUser(User user) { HibernateUntils.add(user); } @Override public void updateUser(User user) { HibernateUntils.update(user); } @Override public void deleteUser(User user) { HibernateUntils.delete(user); } @Override public User findUserByID(int id) { return (User) HibernateUntils.get(User.class, id); } @Override public void deleteUserByID(int id) { Session s = null; Transaction tx = null; try { s = HibernateUntils.getSession(); tx = s.beginTransaction(); String hql="delete User user where user.id=:id"; Query query=s.createQuery(hql); query.setInteger("id", id); query.executeUpdate(); tx.commit(); } catch (Exception e) { if (tx != null) tx.rollback(); throw new RuntimeException(e); } finally { if (s != null) { s.close(); } } } @Override public User findUserByUN(String username) { Session s=null; try{ s=HibernateUntils.getSession(); String hql="from User as user where user.username=:username";//from Object,查找的是对象 Query query=s.createQuery(hql); query.setString("username", username); User user=(User) query.uniqueResult(); return user; }finally{ if(s!=null){ s.close(); } } } }
ProjectTest.java 下面为junit测试
package com.dzq.test; import java.util.Date; import org.junit.Test; import com.dzq.dao.impl.UserDaoImpl; import com.dzq.domain.User; public class ProjectTest { @Test public void testAdd() { UserDaoImpl dao = new UserDaoImpl(); User user = new User(); user.setUsername("xiaodu"); user.setPassword("hello"); user.setRegdate(new Date()); user.setMobile("15820090820"); dao.addUser(user); } @Test public void testUpdate() { UserDaoImpl dao = new UserDaoImpl(); User user = new User(); user = dao.findUserByID(2); user.setUsername("xiaohong"); dao.updateUser(user); } @Test public void testDelete(){ UserDaoImpl dao = new UserDaoImpl(); User user = new User(); user = dao.findUserByID(3); dao.deleteUser(user); } @Test public void testFindUser(){ UserDaoImpl dao = new UserDaoImpl(); User user = new User(); user=dao.findUserByUN("xiaohong"); System.out.println(user.getRegdate()); } @Test public void testDeleteByID(){ UserDaoImpl dao = new UserDaoImpl(); dao.deleteUserByID(2); } }