spring与Hibernate测试
测试服务类,测试事务
package cn.itcast.oa.test;
import javax.annotation.Resource;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.itcast.oa.domain.User;
@Service("testService")
public class TestService {
@Resource
private SessionFactory sessionFactory;
@Transactional
public void saveTwoUsers() {
Session session = sessionFactory.getCurrentSession();
session.save(new User());
// int a = 1 / 0; // 这行会抛异常
session.save(new User());
}
}
测试
package cn.itcast.oa.test;
import org.hibernate.SessionFactory;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringTest {
private ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
// 测试SessionFactory
@Test
public void testSessionFactory() throws Exception {
SessionFactory sessionFactory = (SessionFactory) ac.getBean("sessionFactory");
System.out.println(sessionFactory);
}
// 测试事务
@Test
public void testTransaction() throws Exception {
TestService testService = (TestService) ac.getBean("testService");
testService.saveTwoUsers();
}
}
测试action
Strust配置文件
<package name="default" namespace="/" extends="struts-default">
<!-- 测试用的action,当与Spring整合后,class属性写的就是Spring中bean的名称 -->
<action name="test" class="testAction">
<result name="success">/test.jsp</result>
</action>
</package>
实体类
package cn.itcast.oa.domain;
public class User {
private Long id;
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
映射文件
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="cn.itcast.oa.domain">
<class name="User" table="itcast_user">
<id name="id">
<generator class="native"/>
</id>
<property name="name"/>
</class>
</hibernate-mapping>
package cn.itcast.oa.test;
import javax.annotation.Resource;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import com.opensymphony.xwork2.ActionSupport;
@Controller
@Scope("prototype")
public class TestAction extends ActionSupport {
@Resource
private TestService testService;
@Override
public String execute() throws Exception {
System.out.println("--------> TestAction.execute()");
testService.saveTwoUsers();
return "success";
}
}