MyUser = getJpaTemplate().find(MyUser.class, myUser.getId());
getJpaTemplate().remove(dbMyUser);
}
public void updateMyUser(MyUser myUser) {
MyUser dbMyUser = getJpaTemplate().find(MyUser.class, myUser.getId());
if(myUser.getUserName() != null){
dbMyUser.setUserName(myUser.getUserName());
}
if(myUser.getAddr() != null){
dbMyUser.setAddr(myUser.getAddr());
}
getJpaTemplate().merge(dbMyUser);
}
@SuppressWarnings("unchecked")
public List queryMyUser(String queryString) {
return (List)getJpaTemplate().find(queryString);
}
@SuppressWarnings("unchecked")
public List queryAll() {
return (List)getJpaTemplate().find("from MyUser");
}
}
在Spring框架中集成JPA实例(3)
时间:2011-10-02 百度空间 守护地下铁
因为继承了JpaDaoSupport,索引需要获取一个JpaTemplate来实现访问数据库,在Spring的配置文件 中要注入一个org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean。
Spring的配置文件applicationContext.xml的内容如下所示:
http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">
在META-INF目录下,还要加一个persistence.xml配置文件,如下所示: 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_1_0.xsd"version="1.0">
org.hibernate.ejb.HibernatePersistence
org.shirdrn.entity.MyUser
接着,对增删改查操作进行测试,如下所示:
插入记录:
packageorg.shirdrn.test;
importorg.shirdrn.dao.MyUserDAO;
importorg.shirdrn.entity.MyUser;
importorg.springframework.context.ApplicationContext;
importorg.springframework.context.support.ClassPathXmlApplicationContext;
publicclassTestCreateMyUser{
publicstaticvoidmain(String[]args){
MyUserDAOmyUserDAO=(MyUserDAO)ctx.getBean("myUserDAOImpl");
MyUsermyUser=newMyUser();
myUser.setUserName("JohnXa");
myUser.setPassword("123456");
myUser.setGender("男");
myUser.setAge(newInteger(25));
myUser.setAddr("NewYork");
myUser.setEmail("john@hotmail.com");
myUserDAO.createMyUser(myUser);
}
}
删除记录: packageorg.shirdrn.test;
importorg.shirdrn.dao.MyUserDAO;
importorg.shirdrn.entity.MyUser;
importorg.springframework.context.ApplicationContext;
importorg.springframework.ClassPathXmlApplicationContext;
publicclassTestDeleteMyUser{
publicstaticvoidmain(String[]args){
ApplicationContextctx=newClassPathXml("applicationContext.xml");
MyUserDAOmyUserDAO=(MyUserDAO)ctx.getBean("myUserDAOImpl");
MyUsermyUser=newMyUser();
myUser.setId(newLong(29));
myUserDAO |