spring + jpa + hibernate

来源:互联网 发布:淘宝促销时间表 编辑:程序博客网 时间:2024/05/17 12:21
1. 添加依赖Jar文件。除了必要的spring和Hibernate依赖外,下面的jar必不可少, 否则会抛出异常“No Persistence provider for EntityManager named *”
<dependency><groupId>org.hibernate</groupId><artifactId>hibernate-entitymanager</artifactId><version>4.2.8.Final</version></dependency>



2. spring-jpa-hibernate.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:context="http://www.springframework.org/schema/context"xmlns:aop="http://www.springframework.org/schema/aop"xmlns:tx="http://www.springframework.org/schema/tx"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.2.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-3.2.xsdhttp://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-3.2.xsd"><!-- scan all beans and inject dependence --><context:component-scan base-package="com.myproject"/><!-- add aop support --><aop:aspectj-autoproxy/><!-- jpa --><bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean"><property name="persistenceUnitName" value="example"/></bean><!-- add Transaction support --><bean id="txManager" class="org.springframework.orm.jpa.JpaTransactionManager"><property name="entityManagerFactory" ref="entityManagerFactory"/></bean><!-- scan transaction annotation --><tx:annotation-driven transaction-manager="txManager"/></beans>



3. 在类路径下创建文件夹“META-INF”, 加入文件persistence.xml。 完整的路径是 classpath:META-INF/persistence.xml, 这是jpa的默认配置文件。
<?xml version="1.0" encoding="UTF-8"?><persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd" version="2.0">  <persistence-unit name="example" transaction-type="RESOURCE_LOCAL">      <properties>         <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/>         <property name="hibernate.connection.driver_class" value="org.gjt.mm.mysql.Driver"/>         <property name="hibernate.connection.username" value="root"/>         <property name="hibernate.connection.password" value="admin"/>         <property name="hibernate.connection.url" value="jdbc:mysql://szOIBnchmrkAP1:3306/test?useUnicode=true&amp;characterEncoding=UTF-8"/>         <property name="hibernate.max_fetch_depth" value="3"/>         <!-- create table automatically? -->         <property name="hibernate.hbm2ddl.auto" value="update"/>      </properties>  </persistence-unit></persistence>



4. Entity对象
package com.myproject.example.vo;import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.Id;@Entitypublic class Account {@Id@GeneratedValue //generated automaticallyprivate long id;@Column(length=20, nullable=false)private String username;@Column(length=20, nullable=false)private String password;public long getId() {return id;}public void setId(long 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;}}



5.Dao文件
package com.myproject.example.dao.jpa;import java.util.List;import javax.persistence.EntityManager;import javax.persistence.PersistenceContext;import javax.persistence.Query;import org.springframework.stereotype.Repository;import com.myproject.example.dao.AccountDao;import com.myproject.example.vo.Account;@Repositorypublic class AccountDaoBean implements AccountDao {@PersistenceContextEntityManager em;@Overridepublic Account queryAccountById(int id) {return em.find(Account.class, id);}@SuppressWarnings("unchecked")@Overridepublic List<Account> queryAccount(Account account) {Query q = em.createQuery("select a from Account a where a.username like ?");q.setParameter(1, "%"+account.getUsername()+"%");return q.getResultList();}@Overridepublic int updateAccount(Account account) {em.merge(account);return 0;}@Overridepublic int insertAccount(Account account) {em.persist(account);return 0;}@Overridepublic int deleteAccount(int id) {em.remove(em.getReference(Account.class, id));return 0;}}



6. Service对象包含事务管理
package com.myproject.example.service;import java.util.List;import javax.annotation.Resource;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Propagation;import org.springframework.transaction.annotation.Transactional;import com.myproject.example.dao.AccountDao;import com.myproject.example.vo.Account;@Service@Transactionalpublic class AccountService {@Resourceprivate AccountDao accountDao;//don't need to add transaction in query method @Transactional(propagation=Propagation.NOT_SUPPORTED)public Account Login(String username, String password){System.out.println(username + " want  to login.");Account account = new Account();account.setUsername(username);account.setPassword(password);List<Account> list=  accountDao.queryAccount(account);if(list.size()==1)return list.get(0);else return null;}//in method which already has "throws", we must add rollbackFor if want to rollback for this exception,//otherwise the method will not be rollback@Transactional(rollbackFor=Exception.class)public void reqister(Account account) {accountDao.insertAccount(account);//throw new RuntimeException("==no register");}}



7.web.xml
<?xml version="1.0" encoding="UTF-8"?><web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"><context-param><!-- location of spring config --><param-name>contextConfigLocation</param-name><param-value>classpath:spring.xml</param-value></context-param><!-- initialize spring context--><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><servlet>        <servlet-name>springmvc</servlet-name>        <servlet-class>            org.springframework.web.servlet.DispatcherServlet        </servlet-class>        <init-param>            <param-name>contextConfigLocation</param-name>            <param-value>classpath:springmvc.xml</param-value>        </init-param>        <load-on-startup>1</load-on-startup>    </servlet>    <servlet-mapping>        <servlet-name>springmvc</servlet-name>        <url-pattern>*.do</url-pattern>    </servlet-mapping>        <welcome-file-list>    <welcome-file>/jsp/index.jsp</welcome-file>    </welcome-file-list>          <!-- 解决因EntityManager关闭导致的延迟加载异常-->    <filter>        <filter-name>openEntityManagerInViewFilter</filter-name>        <filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class>    </filter>    <filter-mapping>    <filter-name>openEntityManagerInViewFilter</filter-name>    <url-pattern>/*</url-pattern>    </filter-mapping></web-app>




8.单元测试
@Testpublic void test(){try {ApplicationContext ac=new ClassPathXmlApplicationContext("spring-jpa-hibernate.xml");AccountService accountService =(AccountService)ac.getBean("accountService");Account account = new Account();account.setUsername("tom");account.setPassword("117");accountService.reqister(account);} catch (Exception e) {e.printStackTrace();}}
原创粉丝点击