Hibernate【3】——Service层
1:整体目录
(1)完成UserSerivce接口
(2)完成UserSerivceImpl类,继承UserSerivce接口
(3)写测试类
2:UserSerivce接口
1 package com.demo.service; 2 3 import java.util.List; 4 5 import com.demo.model.User; 6 7 public interface UserService { 8 /** 9 * 添加用户 10 * @param user 11 * @return 12 */ 13 public boolean add(User user); 14 15 /** 16 * 修改用户 17 * @param user 18 * @return 19 */ 20 public boolean update(User user); 21 22 /** 23 * 删除用户 24 * @param user 25 * @return 26 */ 27 public boolean delete(User user); 28 29 /** 30 * 根据id获取用户 31 * @param obj 32 * @param id 33 * @return 34 */ 35 public User getById(Class obj,int id); 36 37 /** 38 * 统计符合一定条件用户的数量 39 * @param hql 40 * @param param 41 * @return 42 */ 43 public int getCount(String hql,String[] param); 44 45 /** 46 * 查询符合一定条件的用户 47 * @param hql 48 * @param param 49 * @return 50 */ 51 public List<User> query(String hql,String[] param); 52 53 }
3:UserSerivceImpl类
package com.demo.service; import java.util.List; import com.demo.dao.BaseDAO; import com.demo.model.User; public class UserServiceImpl implements UserService { private BaseDAO dao = new BaseDAO(); @Override public boolean add(User user) { boolean flag = false; flag = dao.add(user); return flag; } @Override public boolean delete(User user) { boolean flag = false; flag = dao.delete(user); return flag; } @Override public User getById(Class obj, int id) { User u = (User)dao.get(User.class, id); return u; } @Override public int getCount(String hql, String[] param) { int cnt = 0; cnt = dao.getCount(hql, param); return cnt; } @Override public List<User> query(String hql, String[] param) { List<User> list = dao.query(hql, param); return list; } @Override public boolean update(User user) { boolean flag = false; flag = dao.update(user); return flag; } }
4:TestUserSerivce类
注意统计Count的hql语句:
select count(*) from User u where u.userName=?
package com.demo.test; import com.demo.model.User; import com.demo.service.UserService; import com.demo.service.UserServiceImpl; public class TestUserService { public static void main(String[] args) { UserService us = new UserServiceImpl(); //test add User user1 = new User(); user1.setUserName("asdf"); user1.setUserPwd("1234"); us.add(user1); //test delete User user2 = new User(); user2.setId(3); us.delete(user2); //test getById User user3 = us.getById(User.class, 4); System.out.println(user3.getId()+"-->"+user3.getUserName()+"-->"+user3.getUserPwd()); //test Count String[] param = {"asdf"}; int cnt = us.getCount("select count(*) from User u where u.userName=?", param); System.out.println("共有asdf "+Integer.toString(cnt)+" 个。"); //test query //test update User user4 = new User(); user4.setId(4); user4.setUserPwd("000000"); us.update(user4); } }
![字节跳动内推](https://img2020.cnblogs.com/blog/323808/202004/323808-20200415172728571-1992447742.jpg)
找我内推: 字节跳动各种岗位
作者:
ZH奶酪(张贺)
邮箱:
cheesezh@qq.com
出处:
http://www.cnblogs.com/CheeseZH/
*
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。