热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

spring+jpa+hibernate

1.添加依赖Jar文件。除了必要的spring和Hibernate依赖外,下面的jar必不可少,否则会抛出异常“NoPersistenceprovide
1. 添加依赖Jar文件。除了必要的spring和Hibernate依赖外,下面的jar必不可少, 否则会抛出异常“No Persistence provider for EntityManager named *”


org.hibernate
hibernate-entitymanager
4.2.8.Final






2. spring-jpa-hibernate.xml


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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">




















3. 在类路径下创建文件夹“META-INF”, 加入文件persistence.xml。 完整的路径是 classpath:META-INF/persistence.xml, 这是jpa的默认配置文件。



xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd" version="2.0">



















4. Entity对象


package com.myproject.example.vo;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity
public class Account {
@Id
@GeneratedValue //generated automatically
private 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;
@Repository
public class AccountDaoBean implements AccountDao {
@PersistenceContext
EntityManager em;
@Override
public Account queryAccountById(int id) {
return em.find(Account.class, id);
}
@SuppressWarnings("unchecked")
@Override
public List queryAccount(Account account) {
Query q = em.createQuery("select a from Account a where a.username like ?");
q.setParameter(1, "%"+account.getUsername()+"%");
return q.getResultList();
}
@Override
public int updateAccount(Account account) {
em.merge(account);
return 0;
}
@Override
public int insertAccount(Account account) {
em.persist(account);
return 0;
}
@Override
public 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
@Transactional
public class AccountService {
@Resource
private 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 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


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">


contextConfigLocation
classpath:spring.xml



org.springframework.web.context.ContextLoaderListener


springmvc

org.springframework.web.servlet.DispatcherServlet


contextConfigLocation
classpath:springmvc.xml

1


springmvc
*.do


/jsp/index.jsp



openEntityManagerInViewFilter
org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter


openEntityManagerInViewFilter
/*









8.单元测试


@Test
public 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();
}
}

推荐阅读
  • Spring框架《一》简介
    Spring框架《一》1.Spring概述1.1简介1.2Spring模板二、IOC容器和Bean1.IOC和DI简介2.三种通过类型获取bean3.给bean的属性赋值3.1依赖 ... [详细]
  • XML介绍与使用的概述及标签规则
    本文介绍了XML的基本概念和用途,包括XML的可扩展性和标签的自定义特性。同时还详细解释了XML标签的规则,包括标签的尖括号和合法标识符的组成,标签必须成对出现的原则以及特殊标签的使用方法。通过本文的阅读,读者可以对XML的基本知识有一个全面的了解。 ... [详细]
  • 解决java.lang.IllegalStateException: ApplicationEventMulticaster not initialized错误的方法和原因
    本文介绍了解决java.lang.IllegalStateException: ApplicationEventMulticaster not initialized错误的方法和原因。其中包括修改包名、解决service name重复、处理jar包冲突和添加maven依赖等解决方案。同时推荐了一个人工智能学习网站,该网站内容通俗易懂,风趣幽默,值得一看。 ... [详细]
  • 本文讨论了在Spring 3.1中,数据源未能自动连接到@Configuration类的错误原因,并提供了解决方法。作者发现了错误的原因,并在代码中手动定义了PersistenceAnnotationBeanPostProcessor。作者删除了该定义后,问题得到解决。此外,作者还指出了默认的PersistenceAnnotationBeanPostProcessor的注册方式,并提供了自定义该bean定义的方法。 ... [详细]
  • 本文介绍了Android 7的学习笔记总结,包括最新的移动架构视频、大厂安卓面试真题和项目实战源码讲义。同时还分享了开源的完整内容,并提醒读者在使用FileProvider适配时要注意不同模块的AndroidManfiest.xml中配置的xml文件名必须不同,否则会出现问题。 ... [详细]
  • SpringMVC接收请求参数的方式总结
    本文总结了在SpringMVC开发中处理控制器参数的各种方式,包括处理使用@RequestParam注解的参数、MultipartFile类型参数和Simple类型参数的RequestParamMethodArgumentResolver,处理@RequestBody注解的参数的RequestResponseBodyMethodProcessor,以及PathVariableMapMethodArgumentResol等子类。 ... [详细]
  • Activiti7流程定义开发笔记
    本文介绍了Activiti7流程定义的开发笔记,包括流程定义的概念、使用activiti-explorer和activiti-eclipse-designer进行建模的方式,以及生成流程图的方法。还介绍了流程定义部署的概念和步骤,包括将bpmn和png文件添加部署到activiti数据库中的方法,以及使用ZIP包进行部署的方式。同时还提到了activiti.cfg.xml文件的作用。 ... [详细]
  • Java如何导入和导出Excel文件的方法和步骤详解
    本文详细介绍了在SpringBoot中使用Java导入和导出Excel文件的方法和步骤,包括添加操作Excel的依赖、自定义注解等。文章还提供了示例代码,并将代码上传至GitHub供访问。 ... [详细]
  • Spring源码解密之默认标签的解析方式分析
    本文分析了Spring源码解密中默认标签的解析方式。通过对命名空间的判断,区分默认命名空间和自定义命名空间,并采用不同的解析方式。其中,bean标签的解析最为复杂和重要。 ... [详细]
  • 原文地址:https:www.cnblogs.combaoyipSpringBoot_YML.html1.在springboot中,有两种配置文件,一种 ... [详细]
  • 本文介绍了在SpringBoot中集成thymeleaf前端模版的配置步骤,包括在application.properties配置文件中添加thymeleaf的配置信息,引入thymeleaf的jar包,以及创建PageController并添加index方法。 ... [详细]
  • Android系统移植与调试之如何修改Android设备状态条上音量加减键在横竖屏切换的时候的显示于隐藏
    本文介绍了如何修改Android设备状态条上音量加减键在横竖屏切换时的显示与隐藏。通过修改系统文件system_bar.xml实现了该功能,并分享了解决思路和经验。 ... [详细]
  • Android开发实现的计时器功能示例
    本文分享了Android开发实现的计时器功能示例,包括效果图、布局和按钮的使用。通过使用Chronometer控件,可以实现计时器功能。该示例适用于Android平台,供开发者参考。 ... [详细]
  • 在Xamarin XAML语言中如何在页面级别构建ControlTemplate控件模板
    本文介绍了在Xamarin XAML语言中如何在页面级别构建ControlTemplate控件模板的方法和步骤,包括将ResourceDictionary添加到页面中以及在ResourceDictionary中实现模板的构建。通过本文的阅读,读者可以了解到在Xamarin XAML语言中构建控件模板的具体操作步骤和语法形式。 ... [详细]
  • 本文讨论了在shiro java配置中加入Shiro listener后启动失败的问题。作者引入了一系列jar包,并在web.xml中配置了相关内容,但启动后却无法正常运行。文章提供了具体引入的jar包和web.xml的配置内容,并指出可能的错误原因。该问题可能与jar包版本不兼容、web.xml配置错误等有关。 ... [详细]
author-avatar
yinghccll
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有