hibernate 单独配置

阅读更多

Hibernate配置:

  • 数据库连接配置文件,路径随意

名称为hibernate.cfg.xml

 

// 读取默认配置文件
cfg = new Configuration().configure();

 

 名称为自定义

 

// 读取自定义配置文件
cfg = new Configuration().configure("自定义.xml");

 hibernate.cfg.xml文件示例

 

 



  
  
  
      
          
        com.mysql.jdbc.Driver  
          
        jdbc:mysql://localhost:3306/test  
          
        root  
          
        whenjun  
          
        org.hibernate.dialect.MySQLDialect  
          
          
          
      

 

entity映射文件名称随意,一般为 entity.hbm.xml,路径随意



  
     
 
  
      
          
        	
            
          
          
          
      
  

 entity类

@Entity
@Table(name="user")
public class User implements Serializable{
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Id
	@Column(name = "id", nullable = false)
	private String id;
	
	@Column(length=255) 
	private String username;
	
	@Column(length=255) 
	private String password;
	
	public User(){}
	
	public User(String id,String username,String password){
		this.id=id;
		this.username=username;
		this.password=password;
	}

	public String getId() {
		return id;
	}

	public void setId(String 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;
	}
	
	@Override
	public String toString(){
		return "User [id=" + id + ", username=" + username + ", password=" + password + "]";
	}
}

 test

public class JTest {

	private Configuration cfg = null;

	private SessionFactory factory = null;

	private Session session = null;

	@Before
	public void before() {
		// 读取配置文件
		cfg = new Configuration().configure();

		factory = cfg.buildSessionFactory();

		session = factory.openSession();

		System.out.println("session开启成功");
	}

	@After
	public void after() {
		if (session != null) {
			if (session.isOpen()) {
				// 关闭session
				session.close();
				System.out.println("session关闭");
			}
		}
		if(factory!=null){
			factory.close();
			System.out.println("sessionFactory关闭");
		}
	}
/****
	 * 新增
	 * 
	 * @date 2017年5月4日
	 * @author wanwenjun
	 */
	@Test
	public void save() {
		try {
			session.beginTransaction();

			String id = UUID.randomUUID().toString();
			
			System.out.println(id);
			User user = new User();
			user.setId(id);
			user.setUsername("搜索");
			user.setPassword("2321");

			session.save(user);
			
			// 提交事务
			session.getTransaction().commit();

			System.out.println("添加成功");
		} catch (Exception e) {
			e.printStackTrace();
			// 回滚事务
			session.getTransaction().rollback();
			System.out.println("添加失败,回滚");
		}
	}
}

 

 

 

你可能感兴趣的:(hibernate 单独配置)