1.加hibernate的jar包
2.在模型类中加入注解
代码中的: @Entity---->import javax.persistence.Entity;
@Id----->import javax.persistence.Id;
@GeneratedValue--------->import javax.persistence.GeneratedValue;
是加入的
package cn.com.lrs.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; @Entity public class User { private int id; private String username; private String password; @Id @GeneratedValue 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; } }
3.在项目加入SessionFactory工具类
package cn.com.lrs.util; import org.hibernate.SessionFactory; import org.hibernate.cfg.AnnotationConfiguration; public class HibernateUtil { private static SessionFactory sf; static { sf = new AnnotationConfiguration().configure().buildSessionFactory(); } public static SessionFactory getSessionFactory() { return sf; } }
4.操作---------------------------------------
SessionFactory sf = HibernateUtil.getSessionFactory(); Session s = sf.getCurrentSession(); s.beginTransaction(); long count = (Long)s.createQuery("select count(*) from User u where u.username=:username ") .setString("username", u.getUsername())//设置数值 .uniqueResult();//返回结果 s.getTransaction().commit(); if (count > 0) { return true; } return false;
代替掉以下代码
Class.forName("com.mysql.jdbc.Driver"); Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/spring", "root", "ocsoft"); String sqlQuery = "select count(*) from user where username= ?"; PreparedStatement psQuery = conn.prepareStatement(sqlQuery); psQuery.setString(1,u.getUsername()); ResultSet rs = psQuery.executeQuery(); rs.next(); int count = rs.getInt(1);//拿到字段值 psQuery.close(); conn.close(); if (count > 0) { return true; } return false;
你看看hibernate添加信息多么的简单
SessionFactory sf = HibernateUtil.getSessionFactory(); Session s = sf.getCurrentSession(); s.beginTransaction(); s.save(u); s.getTransaction().commit();
5.创建Junit测试类(具体看附件)
package cn.com.lrs.service; import static org.junit.Assert.*; import org.junit.Test; public class UserManagerTest { @Test public void testExists() { fail("Not yet implemented"); } @Test public void testAdd() { fail("Not yet implemented"); } }