hibernate----初体验

hibernate 主要是和数据库打交道,管理实体类的持久化操作
操作步骤
1.导入hibernate包,如果用maven就方便多了
2.创建实体类
package entity;

public class User {

private int id;
private String username;
private String password;
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.配置实体类的映射文件 xxx.hbm.xml


"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">


    
        
    
    
    


4.配置hibernate的映射文件 hibernate.cfg.xml

"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">



    
    com.mysql.jdbc.Driver
    jdbc:mysql:///shopping
    root
    123456


create

org.hibernate.dialect.MySQL5Dialect

    
    true
        true
   

    
  


5.写测试文件
package text;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import entity.User;

public class text01 {

public static void main(String[] args) {
    Configuration config=new Configuration().configure("hibernate.cfg.xml");
    SessionFactory sessionFactory=config.buildSessionFactory();
    Session session=sessionFactory.openSession();
    Transaction transaction=session.beginTransaction();
    User user =new User();
    user.setUsername("AAA");
    user.setPassword("123456");
    session.save(user);
    session.delete(user);
    transaction.commit();
    session.close();
    
    
}
public static void delete(User user ){
    Configuration config=new Configuration().configure("hibernate.cfg.xml");
    SessionFactory sessionFactory=config.buildSessionFactory();
    Session session=sessionFactory.openSession();
    Transaction ts=session.beginTransaction();
    
    session.delete(1);
    
    ts.commit();
    session.close();
    
    
}

}

你可能感兴趣的:(hibernate----初体验)