In the below example, I will create the basic domain, Dao Interface, Implementation and Test class for JPA implementation.
1. First Create the database schema as shown below:
create table login_user(uuid varchar2(40), user_name varchar2(40), password varchar2(100), first_name varchar2(100), last_name varchar2(100));
2. Create the domain class for the data model shown above:
PersistableId Class
1: package com.jsf.app.persistence.model;
2: import java.io.Serializable;
3: import javax.persistence.Column;
4: import javax.persistence.Id;
5: import javax.persistence.MappedSuperclass;
6: import javax.persistence.PrePersist;
7: import com.jsf.app.utils.UUIDGenerator;
8: @MappedSuperclass
9: public class AbstractIdPersistable implements Serializable {
10: private static final long serialVersionUID = -2722115269874427565L;
11: @Id
12: @Column(name = "UUID")
13: private String id;
14: public String getId() {
15: return id;
16: }
17: public void setId(String id) {
18: this.id = id;
19: }
20: public boolean isNew() {
21: return null == getId();
22: }
23: @PrePersist
24: public void assignUUID() {
25: this.setId(UUIDGenerator.getUUID());
26: }
27: }
Persistable User Class map to LOGIN_USER table.
1: package com.jsf.app.persistence.model;
2: import javax.persistence.Column;
3: import javax.persistence.Entity;
4: import javax.persistence.NamedQueries;
5: import javax.persistence.NamedQuery;
6: import javax.persistence.Table;
7: @Entity
8: @Table(name = "LOGIN_USER")
9: @NamedQueries({
10: @NamedQuery(name = "user.findAll", query = "from User"),
11: @NamedQuery(name = "user.findByUserName", query = "from User u where u.userName = ?") })
12: public class User extends AbstractIdPersistable {
13: private static final long serialVersionUID = -6103795542566301215L;
14: @Column(name = "USER_NAME", nullable = false)
15: private String userName;
16: @Column(name = "PASSWORD", nullable = false)
17: private String password;
18: @Column(name = "FIRST_NAME", nullable = false)
19: private String firstName;
20: @Column(name = "LAST_NAME", nullable = false)
21: private String lastName;
22: public String getUserName() {
23: return userName;
24: }
25: public void setUserName(String userName) {
26: this.userName = userName;
27: }
28: public String getPassword() {
29: return password;
30: }
31: public void setPassword(String password) {
32: this.password = password;
33: }
34: public String getFirstName() {
35: return firstName;
36: }
37: public void setFirstName(String firstName) {
38: this.firstName = firstName;
39: }
40: public String getLastName() {
41: return lastName;
42: }
43: public void setLastName(String lastName) {
44: this.lastName = lastName;
45: }
46: @Override
47: public String toString() {
48: return "[" + this.getId() + ", " + this.getFirstName() + ", "
49: + this.getLastName() + "]";
50: }
51: }
3. Now create a generic persistence dao interface:
1: package com.jsf.app.persistence.dao;
2: import java.util.Collection;
3: public interface AbstractPersistenceDao<Entity> {
4: public Entity findById(String id);
5: public void save(Entity e);
6: public void remove(Entity e);
7: public Collection<Entity> findByNamedQuery(String nameQuery);
8: public Collection<Entity> findByNamedQueryAndParams(String nameQuery,
9: Object... params);
10: }
4. Now create an abstract implementation of the generic persistence dao:
1: package com.jsf.app.persistence.dao.impl;
2: import java.lang.reflect.ParameterizedType;
3: import java.util.Collection;
4: import javax.persistence.EntityManager;
5: import javax.persistence.PersistenceContext;
6: import javax.persistence.Query;
7: import com.jsf.app.persistence.dao.AbstractPersistenceDao;
8: public abstract class AbstractPersistenceDaoImpl<Entity> implements
9: AbstractPersistenceDao<Entity> {
10: @PersistenceContext
11: private EntityManager entityManager;
12: public AbstractPersistenceDaoImpl() {
13: }
14: @SuppressWarnings("unchecked")
15: public Class<Entity> returnEntityClass() {
16: ParameterizedType genericSuperclass = (ParameterizedType) getClass()
17: .getGenericSuperclass();
18: return (Class<Entity>) genericSuperclass.getActualTypeArguments()[0];
19: }
20: @Override
21: public Entity findById(String id) {
22: return entityManager.find(returnEntityClass(), id);
23: }
24: @Override
25: public void save(Entity e) {
26: this.entityManager.persist(e);
27: }
28: @Override
29: public void remove(Entity e) {
30: this.entityManager.remove(e);
31: }
32: @Override
33: @SuppressWarnings("unchecked")
34: public Collection<Entity> findByNamedQuery(String query) {
35: Query q = this.entityManager.createNamedQuery(query);
36: return (Collection<Entity>) q.getResultList();
37: }
38: @Override
39: @SuppressWarnings("unchecked")
40: public Collection<Entity> findByNamedQueryAndParams(String nameQuery,
41: Object... params) {
42: Query q = entityManager.createNamedQuery(nameQuery);
43: int i = 1;
44: for (Object o : params) {
45: q.setParameter(i, o);
46: }
47: return (Collection<Entity>) q.getResultList();
48: }
49: }
5. We can now create our customized Dao Interface and Implementation for our Domain Objects. In this case for our User domain object as shown below:
1: package com.jsf.app.persistence.dao;
2: import java.util.Collection;
3: import com.jsf.app.persistence.model.User;
4: public interface UserDao extends AbstractPersistenceDao<User> {
5: public Collection<User> getAllUser();
6: public void persistChange(User user);
7: }
and Implementation:
1: package com.jsf.app.persistence.dao.impl;
2: import java.util.Collection;
3: import org.springframework.stereotype.Repository;
4: import org.springframework.transaction.annotation.Transactional;
5: import com.jsf.app.persistence.dao.UserDao;
6: import com.jsf.app.persistence.model.User;
7: @Repository("userDao")
8: public class UserDaoImpl extends AbstractPersistenceDaoImpl<User> implements
9: UserDao {
10: public UserDaoImpl() {
11: super();
12: }
13: @Override
14: @SuppressWarnings("unchecked")
15: public Collection<User> getAllUser() {
16: return findByNamedQuery("user.findAll");
17: }
18: @Override
19: @Transactional
20: public void persistChange(User user) {
21: save(user);
22: }
23: }
6. Finally create the test case to test the Dao and Implementation:
1: package com.jsf.app.persistence.dao.impl;
2: import java.util.Collection;
3: import java.util.List;
4: import org.junit.After;
5: import org.junit.Assert;
6: import org.junit.Before;
7: import org.junit.Ignore;
8: import org.junit.Test;
9: import org.junit.runner.RunWith;
10: import org.springframework.beans.factory.annotation.Autowired;
11: import org.springframework.test.context.ContextConfiguration;
12: import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
13: import org.springframework.test.context.transaction.TransactionConfiguration;
14: import org.springframework.transaction.annotation.Transactional;
15: import com.jsf.app.persistence.dao.UserDao;
16: import com.jsf.app.persistence.model.User;
17: @RunWith(SpringJUnit4ClassRunner.class)
18: @ContextConfiguration(locations = { "classpath*:applicationContext.xml" })
19: @TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = false)
20: public class UserDaoTest {
21: @Autowired
22: private UserDao userDao;
23: @Before
24: public void before() {
25: }
26: @After
27: public void after() {
28: }
29: @Test
30: @Transactional
31: @Ignore
32: public void testSaveAllUsers() {
33: User u = new User();
34: u.setFirstName("Joy");
35: u.setLastName("Steward");
36: u.setUserName("joy");
37: u.setPassword("password");
38: userDao.persistChange(u);
39: }
40: @Test
41: public void testGetAllUser() {
42: List<User> users = (List<User>) userDao.getAllUser();
43: Assert.assertNotNull(users);
44: Assert.assertEquals(1, users.size());
45: }
46: @Test
47: public void testNamedQueryAndParam() {
48: Collection<User> users = userDao.findByNamedQueryAndParams(
49: "user.findByUserName", "joy");
50: Assert.assertNotNull(users);
51: Assert.assertEquals(1, users.size());
52: }
53: @Test
54: public void testFindUserById() {
55: User u = userDao.findById("E5429C88F74F4A8C6B13399485587401");
56: Assert.assertNotNull(u);
57: Assert.assertEquals("joy", u.getUserName());
58: }
59: }
Very helpful and clean example. Thanks !!
ReplyDelete