This article, mainly introduce spring and hibernate how to integrate, nonsense will not say much, if do not know Spring and hibernate is what, also please go to ask degree Niang ha. The following steps are set up step by step:
1. Create a new MAVEN project: As for the name of the project, don't introduce it.
Here my idea does not automatically generate the test folder, you need to build it yourself, after the project directory as shown:
2. Below I post the project Pom file:
<project xmlns= "http://maven.apache.org/POM/4.0.0" xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xsi:s chemalocation= "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd" > <modelversion >4.0.0</modelVersion> <groupId>shop</groupId> <artifactId>shop</artifactId> < packaging>war</packaging> <version>1.0-SNAPSHOT</version> <name>shop Maven webapp</ Name> <url>http://maven.apache.org</url> <!--version Control--<properties> <project.b Uild.sourceencoding>utf-8</project.build.sourceencoding> <spring.version>4.2.4.release</ Spring.version> 3. Add bean file in resources, Ioctest.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" xsi:schemalocation= "http://www.springframework.org/ Schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd "><bean id=" Date "class=" Java.util.Date "></bean></beans>
4. Create a new Ioctest test class, such as:@RunWith (Springjunit4classrunner.class) @ContextConfiguration (locations= "Classpath:IocTest.xml") // Bean injection via Annotations public class Ioctest {/ ////In this encounter a long time problem, only suddenly understand spring context // A container is an early instantiation of a bean-managed object in a container. Therefore, in the use of the time is no need to instantiate, direct use can be @Resource private date date;//through the Bean injected object is not required to instantiate the private date date1;// Using the Date object directly, you need to instantiate the @Test public void Testico () {
SYSTEM.OUT.PRINTLN (date); The output System.out.println (date1) of the Bean injection object; Date1=new Date (); System.out.println (date1); System.out.println (date1); }}
The output results are as follows:Sat Jul 16:38:26 CST 2016
Null
Sat Jul 16:38:26 CST 2016
Sat Jul 16:38:26 CST 2016
You see the results, we must understand the role of spring container
Here Spring has tested OK.
Second, spring integration hibernate, here is to say: Spring is through the management Hibernate Localsessionfactorybean object for Hibernate session management
The Pom.xml file above has been added to hibernate, and this is not a separate introduction.
1. Using persistence to generate Hibernate entity model and entity model configuration file
When you are finished configuring persitence, configure the database
Now you can build the entity model and the configuration file:
This generates the model and configuration files, such as:
Here for the unified management of resource files, I put UserEntity.hbm.xml in the resources.
3. First create a new bean file, springcontext.xml
<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "Http://www.springframework.org/schema/beans" xmlns: aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP" xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns: context= "Http://www.springframework.org/schema/context" xmlns:tx= "Http://www.springframework.org/schema/tx" xs i:schemalocation= "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/co Ntext/spring-context-2.5.xsd Http://www.springframework.org/schema/tx Http://www.springframework.org/schema /tx/spring-tx-2.5.xsd "> <!--Auto-scan and assemble bean--<context:component-scan base-package=" Com.fei.shop ">< ;/context:component-scan> <!--Import external properties Files--<context:property-placeholder location= "classpath: Jdbc.properties "/> <!--configuration Sessionfactory--> <bean id= "Sessionfactory" class= "Org.springframework.orm.hibernate5.LocalSessionFactoryBean" > <!--specify Hibe Rnate configuration file Location--<property name= "configlocation" value= "Classpath:hibernate.cfg.xml" ></property> <!--configuring C3P0 database Connection Pool-<property name= "DataSource" > <bean class= "com.mchange.v2.c3p0.c Ombopooleddatasource "> <!--data connection information--<property name=" Jdbcurl "value=" ${jdbcurl } "></property> <property name=" Driverclass "value=" ${driverclass} "></property> <property name= "user" value= "${username}" ></property> <propert name= "password" value = "${password}" ></property> </bean> </property> </bean> <!--configuring declarative Transaction Tubes <bean id= "Txmanager" class= "Org.springframework.orm.hibernate5.HibernateTransactionManager" (using annotations) > <property NAme= "Sessionfactory" ref= "sessionfactory" ></property> </bean> <tx:annotation-driven Transaction-manager= "Txmanager"/></beans>
4. New jdbc.properties Database configuration file
Jdbcurl = Jdbc:mysql://localhost:3306/shop?useunicode=true&characterencoding=utf-8driverclass = Com.mysql.jdbc.DriveruserName = Rootpassword =root
5. New Testdao Layer
Package Com.fei.shop.dao;import com.fei.shop.model.userentity;/** * Created is jing on 16/7/16. */public interface Testdao {public void Save (userentity userentity);}
6. New TESTDAOIML Layer
Package Com.fei.shop.dao;import Com.fei.shop.model.userentity;import Org.hibernate.session;import Org.hibernate.sessionfactory;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.stereotype.service;import org.springframework.transaction.annotation.transactional;/** * Created by Jing on 16/7/16.
* */
@Service //must add Service annotations, or start error, cannot find spring manageable objects @transactional //transaction must also be configured, otherwise the startup will not find the error of the transaction public class Testdaoimpl implements Testdao { @Autowired //bean Object loading annotation injected private sessionfactory sessionfactory; Gets the seesion private Session that is bound to the current thread getsession () { return sessionfactory.getcurrentsession (); } public void Save (userentity userentity) { getsession (). Save (userentity);} }
7. Service Layer
Package Com.fei.shop.service;import Com.fei.shop.model.userentity;import org.springframework.stereotype.service;/ * * Created by Jing on 16/7/11. */public interface Testservice {public void Save (userentity userentity);//used to test hibernate environment}
Serviceimpl
Package Com.fei.shop.service;import Com.fei.shop.dao.testdao;import Com.fei.shop.model.userentity;import Org.hibernate.session;import Org.hibernate.sessionfactory;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.stereotype.repository;import Org.springframework.stereotype.service;import Org.springframework.transaction.annotation.transactional;import javax.annotation.resource;/** * Created by Jing on 16/7/11. * * * * * * * * @Servicepublic class Testimpl implements Testservice { @Autowired private Testdao Testdao; public void Save (userentity userentity) { testdao.save (userentity);} }
Test class:
Package Com.fei.shop.action;import Com.fei.shop.model.userentity;import Com.fei.shop.service.testimpl;import Com.fei.shop.service.testservice;import Jdk.nashorn.internal.ir.annotations.reference;import Org.junit.runner.runwith;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.context.applicationcontext;import Org.springframework.context.support.classpathxmlapplicationcontext;import Org.springframework.test.context.contextconfiguration;import Org.springframework.test.context.junit4.springjunit4classrunner;import javax.annotation.resource;/** * Created by Jing on 16/7/11. */@RunWith (Springjunit4classrunner.class) @ContextConfiguration (locations= "Classpath:SpringContext.xml") public Class Test {@Autowired private testservice testservice; @org. Junit.test public void Testorm () {userentity model=new userentity (); Model.setname ("Test 122"); Model.setsex (1); Testservice.save (model); }}
This is OK, you can run the project to see if the data is saved successfully.Note: In the save time has encountered the problem of Chinese garbled, database connection added a Characterencoding=utf-8 also no use, later was found, MySQL database in the installation of the default database encoding method, how to modify the database encoding method see:MAC Modify the default encoding format MySQL Fix Chinese inserted in MySQL garbled
I am a. NET development, in the self-learning Java, there is no place for everyone to spit groove and correct AH
Use Maven to integrate spring and hibernate for primary contact scholars