1. 程式人生 > >(12)spring4整合Hibernate5_加入service層

(12)spring4整合Hibernate5_加入service層

IBaseDao:

public interface IBaseDao<T> {
public void add(T t);
public void delete(int id);
public void update(T t);
public T load(int id);
public List<T> list(String sql);
public List<T> list(String sql,Object[] args);
public List<T> list(String sql,Object args);
}

注意:(1).使用泛型實現增刪改查,然後多寫幾個list方法,方便呼叫 

BaseDao:

public class BaseDao<T> extends HibernateDaoSupport implements IBaseDao<T>{

	private Class<T> clz;
	
	
	
	@SuppressWarnings("unchecked")
	public Class<T> getClz() {
		if(clz==null) {
			clz = ((Class<T>)
					(((ParameterizedType)(this.getClass().getGenericSuperclass())).getActualTypeArguments()[0]));
		}
		return clz;
	}//獲取泛型的class

	public void setClz(Class<T> clz) {
		this.clz = clz;
	}

	@Resource(name="sessionFactory")
	public void setSuperSessionFactory(SessionFactory sessionFactory) {
super.setSessionFactory(sessionFactory);
	}

@Override
public void add(T t) {
	// TODO 自動生成的方法存根
	this.getHibernateTemplate().save(t);
}

@Override
public void delete(int id) {
	// TODO 自動生成的方法存根
	this.getHibernateTemplate().delete(this.load(id));
}

@Override
public void update(T t) {
	// TODO 自動生成的方法存根
	this.getHibernateTemplate().update(t);
}

@Override
public T load(int id) {
	// TODO 自動生成的方法存根
	return this.getHibernateTemplate().load(getClz(), id);
}

@Override
public List<T> list(String sql) {
	// TODO 自動生成的方法存根
	return list(sql, null);
}

@Override
public List<T> list(String sql, Object[] args) {
	// TODO 自動生成的方法存根
@SuppressWarnings("unchecked")
Query<T> q=this.getSessionFactory().getCurrentSession().createQuery(sql);
for(int i=0;i<args.length;i++) {
q.setParameter(i, args[i]);
}
List<T> list=q.list();
return list;
}
@Override
public List<T> list(String sql, Object args) {
	// TODO 自動生成的方法存根
	return list(sql, new Object[] {args});
}
}

GroupHibernateDao:

@Repository("groupHibernateDao")
public class GroupHibernateDao extends BaseDao<Group> implements IGroupDao {

}

注意:(1).extends BaseDao<Group>就可以實現BaseDao中的方法了,然後implements IGroupDao,在IGoupDao補充一些非公用的方法

UserHibernateDao:

@Repository("userHibernateDao")
public class UserHibernateDao extends BaseDao<User> implements IUserDao {

	@Override
	public long getUserCountByGroup(int gid) {
		// TODO 自動生成的方法存根
		String sql="select count(*) from User where group.id = ?0";
		long count=(Long)this.getSessionFactory().getCurrentSession().createQuery(sql).setParameter(0, gid).uniqueResult();
		return count;
	}

}

注意:(1).?後面要加一個索引

(2).返回的是Long型別

(3).取count最好使用uniqueResult

實體類Group:

@Entity
@Table(name="t_group")
public class Group {
private int id;
private String name;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public int getId() {
	return id;
}
public void setId(int id) {
	this.id = id;
}
public String getName() {
	return name;
}
public void setName(String name) {
	this.name = name;
}

}

注意:(1)[email protected](strategy(策略) = GenerationType(生成型別).IDENTITY)可以防止生成hibernate_sequence這個表

User:

@Entity
@Table(name="t_user")
public class User {
private int id;
private String username;
private String password;
private String nickname;
private Group group;


@ManyToOne
@JoinColumn(name="gid")
public Group getGroup() {
	return group;
}
public void setGroup(Group group) {
	this.group = group;
}
public User(String username, String password, String nickname) {
	super();
	this.username = username;
	this.password = password;
	this.nickname = nickname;
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public int getId() {
	return id;
}

public void setId(int id) {
	this.id = id;
}
public String getUsername() {
	return username;
}
public void setUsername(String username) {
	this.username = username;
}
public String getPassword() {
	return password;
}
public void setPassword(String password) {
	this.password = password;
}
public String getNickname() {
	return nickname;
}
public void setNickname(String nickname) {
	this.nickname = nickname;
}
public User() {
}
@Override
public String toString() {
	return "User [id=" + id + ", username=" + username + ", password=" + password + ", nickname=" + nickname
			+ ", group=" + group + "]";
}



}

IUserService.:

public interface IUserService {
public void add(User user,int gid);
public void delete(int id);
public void update(User user);
public User load(int id);
public List<User> listAllUser();
public List<User> listByGroup(int gid);
}

IGroupService:

public interface IGroupService {
	public void add(Group group);
	public void delete(int id);
	public void update(Group group);
	public Group load(int id);
	public List<Group> listAllGroup();
}

注意:(1).service層實現邏輯處理等,實現網頁具體的功能,dao層只負責操作資料庫方面的,邏輯判斷這些交給service

GroupService:

@Service("groupService")
public class GroupService implements IGroupService {
private IGroupDao groupHibernateDao;
private IUserDao userHibernateDao;



	public IGroupDao getGroupHibernateDao() {
	return groupHibernateDao;
}
@Resource
public void setGroupHibernateDao(IGroupDao groupHibernateDao) {
	this.groupHibernateDao = groupHibernateDao;
}

public IUserDao getUserHibernateDao() {
	return userHibernateDao;
}
@Resource
public void setUserHibernateDao(IUserDao userHibernateDao) {
	this.userHibernateDao = userHibernateDao;
}

	@Override
	public void add(Group group) {
		// TODO 自動生成的方法存根
		groupHibernateDao.add(group);
	}

	@Override
	public void delete(int id) {
		// TODO 自動生成的方法存根
		long count=userHibernateDao.getUserCountByGroup(id);
		if(count>0) {
			throw new UserException("刪除的組還有使用者");
		}
		groupHibernateDao.delete(id);
	}

	@Override
	public void update(Group group) {
		groupHibernateDao.update(group);
	}

	@Override
	public Group load(int id) {
		// TODO 自動生成的方法存根
		return groupHibernateDao.load(id);
	}

	@Override
	public List<Group> listAllGroup() {
		// TODO 自動生成的方法存根
return groupHibernateDao.list("from Group");
	}

}

IUserService:

public interface IUserService {
public void add(User user,int gid);
public void delete(int id);
public void update(User user);
public User load(int id);
public List<User> listAllUser();
public List<User> listByGroup(int gid);
}

UserService:

@Service("userService")
public class UserService implements IUserService {
private IUserDao userHibernateDao;
private IGroupDao groupHibernateDao;




	public IGroupDao getGroupHibernateDao() {
	return groupHibernateDao;
}
	@Resource
public void setGroupHibernateDao(IGroupDao groupHibernateDao) {
	this.groupHibernateDao = groupHibernateDao;
}
	public IUserDao getUserHibernateDao() {
	return userHibernateDao;
}
@Resource
public void setUserHibernateDao(IUserDao userHibernateDao) {
	this.userHibernateDao = userHibernateDao;
}

	@Override
	public void add(User user,int gid) {
		// TODO 自動生成的方法存根
Group g=groupHibernateDao.load(gid);
if(g==null) {
	throw new UserException("新增的使用者組不存在!");	
}
user.setGroup(g);
userHibernateDao.add(user);
	}

	@Override
	public void delete(int id) {
		// TODO 自動生成的方法存根
		userHibernateDao.delete(id);
	}

	@Override
	public void update(User user) {
		// TODO 自動生成的方法存根
		userHibernateDao.update(user);
	}

	@Override
	public User load(int id) {
		// TODO 自動生成的方法存根
		return userHibernateDao.load(id);
	}

	@Override
	public List<User> listAllUser() {
		// TODO 自動生成的方法存根
return userHibernateDao.list("from User");
	}

	@Override
	public List<User> listByGroup(int gid) {
		// TODO 自動生成的方法存根
		return userHibernateDao.list("from User where group.id=?", gid);
	}

}

UserExceptiom:

public class UserException extends RuntimeException{

	/**
	 * 
	 */
	private static final long serialVersionUID = 4047757718230572027L;

	public UserException() {
		super();
		// TODO 自動生成的建構函式存根
	}

	public UserException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
		super(message, cause, enableSuppression, writableStackTrace);
		// TODO 自動生成的建構函式存根
	}

	public UserException(String message, Throwable cause) {
		super(message, cause);
		// TODO 自動生成的建構函式存根
	}

	public UserException(String message) {
		super(message);
		// TODO 自動生成的建構函式存根
	}

	public UserException(Throwable cause) {
		super(cause);
		// TODO 自動生成的建構函式存根
	}

}

測試類:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/beans.xml")
public class TestService {
	@Resource
private IUserService userService;
	@Resource
private IGroupService groupService;

	@Test
	public void testAdd() {
		Group group=new Group();
		group.setName("testservice");
		groupService.add(group);
		User user=new User("testservice","testservice","testservice");
		userService.add(user, group.getId());
	}
	
	@Test
	public void testDelete() {
		try {
			groupService.delete(7);
		} catch (UserException e) {
			// TODO 自動生成的 catch 塊
			e.printStackTrace();
		}
	}
	
	@Test
	public void testUpdate() {
	Group group=new Group();
	group.setId(7);
	group.setName("testserviceupdate");
	groupService.update(group);
	}
	
    @Test
	public void testLoad() {
	
		Group g=groupService.load(7);
		System.out.println(g);
	}
}

專案結構圖如下: