hibernate环境配置

hibernate.cfg.xml文件



    
    
     
    
    com.mysql.jdbc.Driver
    jdbc:mysql:///hibernate
    wshc
    123456
    
    org.hibernate.dialect.MySQLDialect
    
    
    true
    
    true
    
    update
    
    
    
    

student.hbm.xml表的映射配置








    
        
    
    
    
    


action持续层的调用

@WebServlet(value="/studentAction")
public class StudentAction extends HttpServlet{
    private static final long serialVersionUID = 1L;
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        
        String name = new String(req.getParameter("name").getBytes("iso-8859-1"),"utf-8");
        String email = new String(req.getParameter("email").getBytes("iso-8859-1"),"utf-8");
        StudentService studentService = new StudentServiceImpl();
        System.out.println(name + email);
        studentService.insert(name,email);
    }

}

hibernate的session封装

public class GetSession {
    private static SessionFactory sessionFactory;
    static{
        Configuration configure = new Configuration().configure();      
        sessionFactory = configure.buildSessionFactory();
    }   
    public static Session getSession(){     
        return sessionFactory.openSession();
    }
}

dao层调用数据层步骤

public class StudentDaoImpl implements StudentDao{

    @Override
    public void insert(String name, String email) {
        Session session = GetSession.getSession();
    
        Transaction transaction = session.beginTransaction();
        
        Student student = new Student();
        student.setName (name);
        student.setEmail(email);
        session.save(student);
        
        transaction.commit();
        session.close();
    }
}
增、删、改、查(操作增、删、改时要先查询一下)
@Test
    public void test1(){
        //获取session
        Session session = GetSession.getSession();
        //
        Transaction transaction = session.beginTransaction();
        //查询
        Student student = session.get(Student.class, 5);
        student.setName("笑笑");
        //修改
        session.update(student);
        System.out.println(student);
        //删除
        session.delete(student);
        System.out.println(student);
        //增加
        Student student2 = new Student();
        student2.setName("小辉");
        student2.setEmail("[email protected]");
        System.out.println(student2);
        session.save(student2);
        //提交事务
        transaction.commit();
        //释放资源
        session.close();        
    }   
}

你可能感兴趣的:(hibernate环境配置)