在Spring框架下配置JPA

1,MyEclipse8.5新建一个Java Web工程,我这里命名为JpaSpring。在左侧的Package Explorer里面,工程名JpaSpring上鼠标右键 -> MyEclipse ->Add Spring Capabilities,弹出如下对话框


Spring version选择默认的Spring 3.0。中间的多选框勾选项如上图。点击Finish完成Spring的配置。会发现在工程的src包下已经自动生成了applicationContext.xml应用程序上下文文件。

然后同样在左侧的Package Explorer里面,工程名JpaSpring上鼠标右键 -> MyEclipse ->Add JPA Capabilities,弹出如下对话框

由于是先添加了Spring的各个支持库,所以这里默认已经有Spring的支持了,直接点击Next就可以后,如下图:



这和上一篇日志见到的界面一样,不再赘述,仍然点击Next后,如下图:



点击Finish完成配置。此时就会发现在src/META-INF路径下自动生成了persistence.xml。同时applicationContext.xml文件中自动添加了两个id名别为entityManagerFactory和transactionManager的bean。

然后要做的是把applicationContext.xml文件拖入src/MET-INF路径下,也就是和persistence.xml放在一起。最后的包结构如下图:



和上一篇日志差不多,domain下的Test_Account.java是对应于表test_account的持久化类,dao下的Test_AccountDAO.java是数据访问类,test下的TestResult.java是包含主函数的测试类。

持久化类Test_Account.java的代码如下:
import ...........;

@Entity
@Table(name="test_account")
public class Test_Account implements Serializable {

@Id
private String account;
private String password;
private double balance;
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
}

数据访问类Test_AccountDAO.java代码如下:
import .......;

public class Test_AccountDAO extends JpaDaoSupport {

public void save(Test_Account customer) { //插入
this.getJpaTemplate().persist(customer);
}
public void update(Test_Account customer) { //更新
this.getJpaTemplate().merge(customer);
}

public void remove(Test_Account customer){ //删除

JpaTemplate t = this.getJpaTemplate();
t.remove(t.contains(customer) ? customer : t.merge(customer));
//首先判断要删除的对象是否是受控状态,如果不是,则通过merge的返回值,从游离状态转换成受控状态

//这里更新时间2011-5-26 

}

//按照主键查找一个记录
public Test_Account findByKey(String account) {
List list=(List)getJpaTemplate().find("select c from Test_Account c where c.account = ?1",account); 
if(list==null||list.size()==0)return null;
Test_Account temp=(Test_Account)list.get(0);
return temp;
}
//查找所有记录
public List findAllItems()
{
List list =(List)getJpaTemplate().find("select c from Test_Account c"); 
if(list==null||list.size()==0)return null;
return list;
}

public List getQueryResult(double below,String password)
{
List list =(List)getJpaTemplate().find("select c from Test_Account c where c.balance>?1 and c.password=?2",below,password); 
if(list==null||list.size()==0)return null;
return list;
}
//查找所有的账户名
public List findAllAccountname()
{ //这种查询提取只能提取一个属性构成list,比如这里提取两个属性就会报错
List list=(List)getJpaTemplate().find("select c.account from Test_Account c"); 
if(list==null||list.size()==0)return null;
return list;
}
}

测试类TestResult.java代码如下:
import ........;

public class TestResult {


private ClassPathXmlApplicationContext getApplicationContext(){
ClassPathXmlApplicationContext applicationContext=new
ClassPathXmlApplicationContext("META-INF/applicationContext.xml");
return applicationContext;
}

public static void main(String[] args) {
ApplicationContext b=new TestResult().getApplicationContext();
final Test_AccountDAO dao=(Test_AccountDAO)b.getBean("test_accountdao");
Test_Account abc=new Test_Account();
abc.setAccount("hellopeter");
abc.setPassword("jisuanji");
abc.setBalance(2010);
final Test_Account forinsert=abc;

Test_Account med=dao.findByKey("22368");
med.setPassword("bbbbb");
final Test_Account forupdae=med;

TransactionTemplate transactionTemplate=(TransactionTemplate)b.getBean("transactionTemplate");
transactionTemplate.execute(new TransactionCallbackWithoutResult() {
protected void doInTransactionWithoutResult(TransactionStatus status) {
try {
dao.save(forinsert);//插入
dao.update(forupdae);//更新

Test_Account fordelete=dao.findByKey("delete12");
dao.remove(fordelete); //删除

} catch (Exception e) {
e.printStackTrace();
status.setRollbackOnly();
}
}
});
System.out.println("###############################################");
//查询不必放在上面的事务模板里
List allaccountname=dao.findAllAccountname();
for(int i=0;i<allaccountname.size();i++)
{
System.out.println(allaccountname.get(i).toString());
}
System.out.println("###############################################");
List list=dao.findAllItems();
for(int i=0;i<list.size();i++)
{
Test_Account rr=(Test_Account)list.get(i);
System.out.println(rr.getAccount()+" "+rr.getPassword()+" "+rr.getBalance());
}
System.out.println("################################################");
List queryresult=dao.getQueryResult(1000,"jisuanji");//查询余额大于1000,且密码为jisuanji的账户
for(int i=0;i<queryresult.size();i++)
{
Test_Account rr=(Test_Account)queryresult.get(i);
System.out.println(rr.getAccount()+" "+rr.getPassword()+" "+rr.getBalance());
}
}

}

持久化配置文件persistence.xml代码如下:
<?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_1_0.xsd" version="1.0">

<persistence-unit name="JPASpringPU" transaction-type="RESOURCE_LOCAL">
<provider>oracle.toplink.essentials.PersistenceProvider</provider>

<class>domain.Test_Account</class><!-- 自己添加的持久化类 -->

<properties>
<property name = "toplink.jdbc.driver" value = "com.microsoft.sqlserver.jdbc.SQLServerDriver"/>
<property name = "toplink.jdbc.url" value = "jdbc:sqlserver://localhost:1433;DatabaseName=TestDB"/>
<property name = "toplink.jdbc.user" value = "sa"/>
<property name = "toplink.jdbc.password" value = "1234"/>
</properties>
</persistence-unit>

</persistence>

应用程序上下文applicationContext.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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd" xmlns:tx="http://www.springframework.org/schema/tx">


<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
<property name="persistenceUnitName" value="JPASpringPU" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
<!-- <property name="jpaDialect" ref="jpaDialect" /> -->
</bean>


<!-- 上面是自动生成的,下面的2个bean是自己添加的////////////////////////////////////////////////////////////// -->
<bean id="test_accountdao" class="dao.Test_AccountDAO"> <!-- 自己写的dao数据访问类 -->
<property name="entityManagerFactory" ref="entityManagerFactory" />
<!-- 这儿不加这个property执行时会报错,提示加上 -->
</bean>

<bean id="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate">
<property name="transactionManager" ref="transactionManager" />
<!-- 这儿不加这个property执行时会报错,提示加上 -->
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />

</beans>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章