Create POJO and Gen DB table
1.
Create a POJO class
Person (in the src/main/java/**/model 目录下)
package com.mycompany.model;
import org.appfuse.model.BaseObject;
import javax.persistence.*;
@Entity
public class
Person extends
BaseObject {
private Long id;
private String firstName;
private String lastName;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public Long getId() {
return id;
}
@Column(name="first_name", length=50)
public String getFirstName() {
return firstName;
}
@Column(name="last_name", length=50)
public String getLastName() {
return lastName;
}
。。。。。。
}
POJO扩展BaseObject是可选的,但建议扩展它,因为它会强制你必须在POJO里写toString(), equals() and hashCode() 方法。
如果你计划把POJO放进user's session里,或在web service里使用它,那么POJO还应该实现java.io.Serializable接口
2.
添加下列代码到
src/main/resources/hibernate.cfg.xml
文件
<mapping class="com.mycompany.model.Person"/>
保存之后,执行命令:
mvn test-compile hibernate3:hbm2ddl(前提是database要打开),将会在database里看到添加了Person Table
Create Hibernate DAO
1.
创建
DAO
的单元测试
PersonDaoTest(in your src/test/java/**/dao directory)
package com.mycompany.dao;
import org.appfuse.dao.BaseDaoTestCase;
import org.springframework.dao.DataAccessException;
import com.mycompany.model.Person;
import java.util.List;
public class
PersonDaoTest extends BaseDaoTestCase {
private PersonDao personDao = null;
public void setPersonDao(PersonDao personDao) {
this.personDao = personDao;
}
public void testFindPersonByLastName() throws Exception {
List<Person> people = personDao.findByLastName("Raible");
assertTrue(people.size() > 0);
}
public void testAddAndRemovePerson() throws Exception {
Person person = new Person();
person.setFirstName("Country");
person.setLastName("Bry");
person = personDao.save(person);
flush();
person = personDao.get(person.getId());
assertEquals("Country", person.getFirstName());
assertNotNull(person.getId());
log.debug("removing person...");
personDao.remove(person.getId());
flush();
//
测试在
get
被
removed person
时抛出
exception
try {
personDao.get(person.getId());
fail("Person found in database");
} catch (DataAccessException dae) {
log.debug("Expected exception: " + dae.getMessage());
assertNotNull(dae);
}
}
}
2.
DbUnit Maven Plugin
可以用来在测试运行前将数据插入数据库中
,
你只需将需加入的表或记录的信息放到文件
src/test/resources/sample-data.xml
中
,如:
<table name='person'>
<column>id</column>
<column>first_name</column>
<column>last_name</column>
<row>
<value>1</value>
<value>Matt</value>
<value>Raible</value>
</row>
</table>
3. Step 1创建的
PersonDaoTest.java是无法编译的,因为还没有创建PersonDao (
但要养成好习惯,先写单元测试!PersonDao接口及其实现类(in your src/main/java/**/dao directory))。因此我们
创建
PersonDao.java:
package com.mycompany.dao;
import com.mycompany.model.Person;
import java.util.List;
import org.appfuse.dao.GenericDao;
//
注:扩展
GenericDao
则包含了它的
CRUD
方法!!
public interface
PersonDao extends GenericDao<Person, Long> {
public List<Person> findByLastName(String lastName);
}
PersonDaoHibernate.java:
package com.mycompany.dao.hibernate;
import com.mycompany.model.Person;
import com.mycompany.dao.PersonDao;
import org.appfuse.dao.hibernate.GenericDaoHibernate;
import java.util.List;
public class
PersonDaoHibernate extends GenericDaoHibernate<Person, Long> implements PersonDao {
public PersonDaoHibernate() {
super(Person.class);
}
public List<Person> findByLastName(String lastName) {
return getHibernateTemplate().find("from Person where lastName=?", lastName);
}
}
4.
在
src/
main
/
webapp
/
WEB-INF/applicationContext
.xml
中
添加下列代码来定义
personDao bean:
<bean id="personDao" class="com.mycompany.dao.hibernate.PersonDaoHibernate">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
5.
执行命令
mvn test -Dtest=PersonDaoTest
来进行单元测试
注:执行命令
mvn test是运行所有单元测试
Create Service
在创建了DAO之后,下面的步骤是Manager Service class,它的作用是作为persistence (DAO) layer and the web layer 之间的桥梁,使presentation layer和database layer松耦合(例如i.e. for Swing apps and web services)。
Managers
就是用来放你的
business logic
的地方!
1.
创建
PersonManager interface
(
in your src/main/java/**/service directory
)
package com.mycompany.service;
import com.mycompany.model.Person;
import java.util.List;
import org.appfuse.service.GenericManager;
public interface
PersonManager extends GenericManager<Person, Long> {
public List<Person> findByLastName(String lastName);
}
为什么要扩展
GenericManager??
这是因为
GenericManager
包含了
CRUD
的一些方法,你也可以不扩展它,自己写!
2.
Create manager
单元测试
PersonManagerImplTest
注意:该单元测试使用了
mock objects
,这是为了使你的
tests
不依赖
external dependencies
,也就是说你不需要创建一个
database
也可以
run these tests。这样做就使得在一个大的项目里,DAO和manager分工给不同的人来开发,那么开发manager的人甚至可以在dao impletement完成之前就可以写好manager的单元测试。
本例中使用的
mock objects
是
jMock(
另外一个使用比较广泛的mock object library是EasyMock)
PersonManagerImplTest.java
package com.mycompany.service.impl;
。。。。
public class
PersonManagerImplTest extends BaseManagerMockTestCase {
private PersonManagerImpl manager = null;
private Mock dao = null;
private Person person = null;
protected void setUp() throws Exception {
dao = new Mock(PersonDao.class);
manager = new PersonManagerImpl((PersonDao) dao.proxy());
}
protected void tearDown() throws Exception {
manager = null;
}
public void testGetPerson() {
log.debug("testing getPerson");
Long id = 7L;
person = new Person();
// set expected behavior on dao
//!!
关键方法
dao.expects(once()).method("get")
.with(eq(id))
.will(returnValue(person));
Person result = manager.get(id);
assertSame(person, result);
}
public void testGetPersons() {
log.debug("testing getPersons");
List people = new ArrayList();
// set expected behavior on dao
dao.expects(once()).method("getAll")
.will(returnValue(people));
List result = manager.getAll();
assertSame(people, result);
}
public void testFindByLastName() {
log.debug("testing findByLastName");
List people = new ArrayList();
String lastName = "Smith";
// set expected behavior on dao
dao.expects(once()).method("findByLastName")
.with(eq(lastName))
.will(returnValue(people));
List result = manager.findByLastName(lastName);
assertSame(people, result);
}
public void testSavePerson() {
log.debug("testing savePerson");
person = new Person();
// set expected behavior on dao
dao.expects(once()).method("save")
.with(same(person))
.will(returnValue(person));
manager.save(person);
}
public void testRemovePerson() {
log.debug("testing removePerson");
Long id = 11L;
person = new Person();
// set expected behavior on dao
dao.expects(once()).method("remove")
.with(eq(id))
.isVoid();
manager.remove(id);
}
}
3.
Create Manager implement class PersonManagerImpl
package com.mycompany.service.impl;
。。。。
public class
PersonManagerImpl extends GenericManagerImpl<Person, Long> implements PersonManager {
PersonDao personDao;
public PersonManagerImpl(PersonDao personDao) {
super(personDao);
this.personDao = personDao;
}
public List<Person> findByLastName(String lastName) {
return personDao.findByLastName(lastName);
}
}
4.
在
src/
main
/
webapp
/
WEB-INF/applicationContext
.xml
中
添加下列代码来定义
personDao bean
<bean id="personManager" class="com.mycompany.service.impl.PersonManagerImpl">
<constructor-arg ref="personDao"/>
</bean>
5.
执行命令
mvn test -Dtest=PersonManagerImplTest
来进行单元测试
注:执行命令
mvn test是运行所有单元测试