Use Spring to integrate Hibernate and implement the function of adding, deleting, modifying, and querying data tables. springhibernate
1.1Problem
Use Spring to integrate Hibernate and add, delete, modify, and query the tariff table.
1.2Solution
To integrate Hibernate with Spring, follow these steps:
1.3Procedure
To implement this case, follow these steps.
The environment is eclipse, jdk 7.0, Tomcat7.0, Spring 3.2, and Hibernate 3.2.
Step 1: import package
Create a WEB project SpringHibernate and import the database driver package, Hibernate development kit, and Spring development kit. The structure of the package in the project is as follows:
Then, add it to the class compilation.
Hibernate 3.2 jar package download: http://yunpan.cn/cmRG5gzdMtGMX access password 3747
Spring 3.2 jar package download: http://yunpan.cn/cdXTcJtZfJqQk access password 6c96
Mysql jar package: http://yunpan.cn/cmv3BGe9CkUr3 access password 3601
Step 2: Configure applicationContext. xml
Introduce the Spring configuration file applicationContext. xml and place it in the src root path. Configure the data source, SessionFactory, enable component scanning, and declarative transactions in this file. The Code is as follows:
<? 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: tx = "http://www.springframework.org/schema/tx" xmlns: aop = "http://www.springframework.org/schema/aop" xmlns: context = "http://www.springframework.org/schema/context" xmlns: jee = "http://www.springframework.org/schema/jee" xsi: schemaLocation = "http://www.springframework.org/schema/tx http: // Www.springframework.org/schema/tx/spring-tx-2.5.xsd 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.springf Ramework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd "> <! -- Configure the data source --> <bean id = "ds" class = "com. mchange. v2.c3p0. ComboPooledDataSource" destroy-method = "close"> <! -- Configure the connection parameters --> <property name = "jdbcUrl" value = "jdbc: mysql: // localhost: 3306/cnblogs "/> <property name =" driverClass "value =" com. mysql. jdbc. driver "/> <property name =" user "value =" root "/> <property name =" password "value =" 123456 "/> <! -- Configure the connection pool --> <property name = "initialPoolSize" value = "3"/> <property name = "maxPoolSize" value = "10"/> <property name = "minPoolSize" value = "1"/> <property name = "acquireIncrement" value = "3"/> <property name = "maxIdleTime" value = "60"/> </bean> <! -- Configure SessionFactory --> <bean id = "sessionFactory" class = "org. springframework. orm. hibernate3.LocalSessionFactoryBean"> <! -- Dependent data source --> <property name = "dataSource" ref = "ds"/> <! -- Hibernate framework configuration --> <property name = "hibernateProperties"> <props> <prop key = "hibernate. dialect "> org. hibernate. dialect. mySQLDialect </prop> <prop key = "hibernate. show_ SQL "> true </prop> <prop key =" hibernate. formate_ SQL "> true </prop> </props> </property> <property name =" mappingResources "> <list> <value> com/souvc/entity/Cost. hbm. xml </value> </list> </property> </bean> <! -- Enable annotation scanning --> <context: component-scan base-package = "com. souvc"/> <! -- Declarative transaction management, in the form of AOP --> <bean id = "txManager" class = "org. springframework. orm. hibernate3.HibernateTransactionManager "> <property name =" sessionFactory "ref =" sessionFactory "/> </bean> <tx: advice id = "txAdvice" transaction-manager = "txManager"> <tx: attributes> <tx: method name = "update *" propagation = "REQUIRED"/> <tx: method name = "delete *" propagation = "REQUIRED"/> <tx: method name = "add *" propagation = "REQUIRED"/> <tx: method name = "load *" read-only = "true"/> <tx: method name = "execute" propagation = "REQUIRED"/> </tx: attributes> </tx: advice> <aop: config proxy-target-class = "true"> <aop: advisor advice-ref = "txAdvice" pointcut = "within (com. souvc. action. *) "/> </aop: config> </beans>
Step 3: Create an object class and ing File
Create the com. souvc. entity package, and create the object class and ing file under the package. The Cost code of the object class is as follows:
Package com. souvc. entity; import java. util. date;/*** fee entity class */public class Cost {private Integer id; // primary key private String name; // fee name private Integer baseDuration; // private Double baseCost; // basic fee private Double unitCost; // unit fee private String status; // status private String descr; // fee description private Date createTime; // create Date private Date startTime; // enable Date private String costType; // billing type 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;} public Integer getBaseDuration () {return baseDuration;} public void setBaseDuration (Integer baseDuration) {this. baseDuration = baseDuration;} public Double getBaseCost () {return baseCost;} public void setBaseCost (Double baseCost) {this. baseCost = baseCost;} public Double getUnitCost () {return unitCost;} public void setUnitCost (Double unitCost) {this. unitCost = unitCost;} public String getStatus () {return status;} public void setStatus (String status) {this. status = status;} public String getDescr () {return descr;} public void setDescr (String descr) {this. descr = descr;} public Date getCreateTime () {return createTime;} public Date getStartTime () {return startTime;} public void setStartTime (Date startTime) {this. startTime = startTime;} public void setCreateTime (Date createTime) {this. createTime = createTime;} public String getCostType () {return costType;} public void setCostType (String costType) {this. costType = costType ;}}
The Cost. hbm. xml code of the ing file is as follows:
<? Xml version = "1.0" encoding = "UTF-8"?> <! DOCTYPE hibernate-mapping PUBLIC "-// Hibernate/Hibernate DTD ing DTD 3.0 // EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
Register the ing file in applicationContext. xml. The Code is as follows:
<property name="mappingResources"> <list> <value>com/souvc/entity/Cost.hbm.xml</value> </list> </property>
Step 4:
Create the com. souvc. dao package, and create the DAO interface under the package to declare the method for adding, deleting, modifying, and querying. The Code is as follows:
package com.souvc.dao;import java.util.List;import com.souvc.entity.Cost;public interface ICostDao { List<Cost> findAll(); Cost findById(int id); void save(Cost cost); void update(Cost cost); void delete(int id);}
Create the DAO implementation class CostDaoImpl, which inherits from HibernateDaoSupport and implements the interface ICostDao. The Code is as follows:
package com.souvc.dao;import java.util.List;import javax.annotation.Resource;import org.hibernate.SessionFactory;import org.springframework.orm.hibernate3.support.HibernateDaoSupport;import org.springframework.stereotype.Repository;import com.souvc.entity.Cost;@SuppressWarnings("unchecked")@Repositorypublic class CostDaoImpl extends HibernateDaoSupport implements ICostDao { @Resource public void setSF(SessionFactory sf) { super.setSessionFactory(sf); } @Override public List<Cost> findAll() { String hql = "from Cost"; return getHibernateTemplate().find(hql); } @Override public Cost findById(int id) { return (Cost) getHibernateTemplate().get(Cost.class, id); } @Override public void save(Cost cost) { getHibernateTemplate().save(cost); } @Override public void update(Cost cost) { getHibernateTemplate().update(cost); } @Override public void delete(int id) { Cost c = new Cost(); c.setId(id); getHibernateTemplate().delete(c); }}
Step 5: Test
Under the com. souvc. dao package, create the JUNIT test class TestDao and write the additional, deleted, and modified charges respectively.
Check the test methods and execute these methods for testing. The Code is as follows:
Package com. souvc. dao; import java. util. list; import org. junit. test; import org. springframework. context. applicationContext; import org. springframework. context. support. classPathXmlApplicationContext; import com. souvc. entity. cost;/***** Class Name: TestDao * Description: Test class * developer: souvc * Creation Time: 1:01:44 * release version: v3.0 */public class TestDao {private String conf = "applicationContext. xml ";/*** Method Name: test1 * Details: Query all * developers: souvc * Creation Time: 12:59:30 * description of parameters * description of returned values * description of conditions for this exception */@ Test public void test1 () {ApplicationContext ctx = new ClassPathXmlApplicationContext (conf ); ICostDao dao = (ICostDao) ctx. getBean ("costDaoImpl"); List <Cost> list = dao. findAll (); for (Cost c: list) {System. out. println (c. getId () + "" + c. getName () ;}}/*** Method Name: test2 * Details: Query * developer: souvc * creation time by id: 1:00:07 * description of parameters * description of returned values * description of conditions for this exception */@ Test public void test2 () {ApplicationContext ctx = new ClassPathXmlApplicationContext (conf ); ICostDao dao = (ICostDao) ctx. getBean ("costDaoImpl"); Cost c = dao. findById (1); System. out. println (c. getId () + "" + c. getName ();}/*** Method Name: test3 * Details: Add * developer: souvc * Creation Time: 1:00:32 * description of parameters * description of returned values * description of conditions for this exception */@ Test public void test3 () {ApplicationContext ctx = new ClassPathXmlApplicationContext (conf ); ICostDao dao = (ICostDao) ctx. getBean ("costDaoImpl"); Cost c = new Cost (); c. setName ("aaa"); c. setBaseDuration (20); c. setBaseCost (2.0); c. setUnitCost (0.2); c. setCostType ("1"); c. setStatus ("0"); dao. save (c);}/*** Method Name: test4 * Details: Update * developer: souvc * Creation Time: 1:00:59 * description of parameters * description of returned values * description of conditions for this exception */@ Test public void test4 () {ApplicationContext ctx = new ClassPathXmlApplicationContext (conf ); ICostDao dao = (ICostDao) ctx. getBean ("costDaoImpl"); Cost c = dao. findById (1); c. setName ("bbb"); dao. update (c);}/*** Method Name: test5 * Details: delete * developer: liuhf * Creation Time: 1:01:19 * description of parameters * description of returned values * description of conditions for this exception */@ Test public void test5 () {ApplicationContext ctx = new ClassPathXmlApplicationContext (conf ); ICostDao dao = (ICostDao) ctx. getBean ("costDaoImpl"); dao. delete (1 );}}
Table creation statement:
CREATE TABLE `cost` ( `id` int(10) NOT NULL auto_increment, `name` varchar(50) default NULL, `base_duration` int(11) default NULL, `unit_cost` double(10,0) default NULL, `status` varchar(10) default NULL, `descr` varchar(20) default NULL, `creatime` date default NULL, `startime` date default NULL, `cost_type` varchar(10) default NULL, `base_cost` double(10,0) default NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
The source code is as follows:
Http://yunpan.cn/cmvceCwSyjbXi access password 3930