(1)常用HibernateTemplate类的API【users表(id/username/password)】
(A)HibernateTemplate.save()/delete()/update():增、删、改
(B)HibernateTemplate.get()/load():根据ID查询
(C)HibernateTemplate.find():根据任意条件查询
(D)HibernateTemplate.deleteAll():批删
(E)HibernateTemplate.execute(万能):分页查询多个对象
接着写映射文件User,hbm.xml:
接着写配置文件applicationContext.xml:
接着写UserDao:
最后写测试类:
(A)HibernateTemplate.save()/delete()/update():增、删、改
(B)HibernateTemplate.get()/load():根据ID查询
(C)HibernateTemplate.find():根据任意条件查询
(D)HibernateTemplate.deleteAll():批删
(E)HibernateTemplate.execute(万能):分页查询多个对象
(F)HibernateTemplate.execute(万能):查询出一个整型值
接下来用代码实现:
首先写实体类:User
package com.spring_hibernate.demo2;
/*
* 用户(POJO)
*/
public class User {
private Integer id;//编号
private String name;//姓名
public User(){}
public User(String name) {
super();
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
接着写映射文件User,hbm.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.spring_hibernate.demo2">
<class name="User" table="users">
<id name="id" column="id">
<generator class="native"/>
</id>
<property name="name" column="name"/>
</class>
</hibernate-mapping>
接着写配置文件applicationContext.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<!-- 配置c3p0连接池 -->
<bean id="comboPooledDataSourceID" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
<property name="jdbcUrl" value="jdbc:mysql://127.0.0.1:3306/example_db"/>
<property name="user" value="root"/>
<property name="password" value="04010"/>
</bean>
<!-- 配置SessionFctory -->
<bean id="localSessionFactoryBeanID" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="comboPooledDataSourceID"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.cache.provider_class">org.hibernate.cache.HashtableCacheProvider</prop>
<prop key="hibernate.cache.use_query_cache">true</prop>
</props>
</property>
<property name="mappingResources">
<list>
<value>com/spring_hibernate/demo2/User.hbm.xml</value>
</list>
</property>
</bean>
<!-- 配置HibernateTemplate -->
<bean id="hibernateTemplateID" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="localSessionFactoryBeanID"/>
</bean>
<!-- 配置UserDao(目标对象) -->
<bean id="userDaoID" class="com.spring_hibernate.demo2.UserDao">
<property name="ht" ref="hibernateTemplateID"/>
</bean>
<!-- 配置hibernate事务管理器 -->
<bean id="hibernateTransactionManagerID" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="localSessionFactoryBeanID"/>
</bean>
<!-- 配置事务增强(服务对象) -->
<tx:advice id="txAdvice" transaction-manager="hibernateTransactionManagerID">
<tx:attributes>
<tx:method name="*"/>
</tx:attributes>
</tx:advice>
<!-- 配置AOP -->
<aop:config>
<aop:pointcut id="op" expression="execution(public void com.spring_hibernate.demo2.UserDao.*(..) throws Exception)"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="op"/>
</aop:config>
</beans>
接着写UserDao:
package com.spring_hibernate.demo2;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
/*
* 持久层
*/
public class UserDao {
//HibernateTemplate模板
private HibernateTemplate ht;
//注入方法
public void setHt(HibernateTemplate ht) {
this.ht = ht;
}
//增加用户
public void add(User user) throws Exception{
ht.save(user);
}
//根据ID查询用户
public User findById(Integer id) throws Exception{
return (User) ht.get(User.class,id);
}
//修改用户
public void update(User user) throws Exception{
ht.update(user);
}
//删除用户
public void delete(User user) throws Exception{
ht.delete(user);
}
//查询以"精"结尾的用户
public List<User> findAll(String hql,Object[] params) throws Exception{
return ht.find(hql,params);
}
//批量删除
public void deleteAll(Collection<User> users) throws Exception{
ht.deleteAll(users);
}
//分页查询用户
public List<User> findAllFy(final Integer start,final Integer size) throws Exception{
return (List<User>) ht.execute(new HibernateCallback(){
public Object doInHibernate(Session session)throws HibernateException, SQLException {
String hql = "from User";
Query query = session.createQuery(hql);
query.setFirstResult(start);
query.setMaxResults(size);
return query.list();
}
});
}
//获取用户总数
public Integer getTotalUser() throws Exception{
return (Integer) ht.execute(new HibernateCallback(){
public Object doInHibernate(Session session)throws HibernateException, SQLException {
String hql = "select count(u) from User u";
Query query = session.createQuery(hql);
Long temp = (Long) query.uniqueResult();
return temp.intValue();
}
});
}
}
最后写测试类:
package com.spring_hibernate.demo2;
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/*
* 测试
*/
public class TestSpring {
public static void main(String[] args) throws Exception {
User user = new User("小黄");
ApplicationContext ac = new ClassPathXmlApplicationContext(new String[]{"com/spring_hibernate/demo2/applicationContext.xml"});
UserDao userDao = (UserDao) ac.getBean("userDaoID");
//userDao.add(user);
user = userDao.findById(2);
System.out.println(user.getName());
user.setName("小小");
userDao.update(user);
userDao.delete(user);
String hql = "from User u where u.username like ?";
Object[] params = {"%小"};
List<User> userList = userDao.findAll(hql,params);
userDao.deleteAll(userList);
List<User> list = userDao.findAllFy(2,2);
System.out.println("共有" + userDao.getTotalUser()+"个人");
}
}