hibernate入门学习

1.实体类

package domain;
public class user {
private int id;
private String username;
private  String password;
@Override
public String toString() {
return "user [id=" + id + ", username=" + username + ", password=" + password + "]";
}
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;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}

}

2.User.hbm.xml

作用:配置映射,生成主键

<!-- 配置类和表结构的映射 -->
<class name="domain.user" table="user">
<!-- 配置id 
见到name属性,JavaBean的属性
见到column属性,是表结构的字段
-->
<id name="id" column="id">
<!-- 主键的生成策略 -->
<generator class="native"/>
</id>

<!-- 配置其他的属性 -->
<property name="username" column="username" type="string"></property>
<property name="password" column="password" type="string"></property>

</class>

3.hibernate.cfg.xml

作用:与数据库建立连接

<!-- 记住:先配置SessionFactory标签,一个数据库对应一个SessionFactory标签 -->
<session-factory>

<!-- 必须要配置的参数有5个,4大参数,数据库的方言 -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql:///hibernate_day01</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">123</property>

<!-- 数据库的方言 -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>

<!-- 可选配置 -->
<!-- 显示SQL语句,在控制台显示 -->
<property name="hibernate.show_sql">true</property>
<!-- 格式化SQL语句 -->
<property name="hibernate.format_sql">true</property>

<!-- 生成数据库的表结构 
update:如果没有表结构,创建表结构。如果存在,不会创建,添加数据
-->
<property name="hibernate.hbm2ddl.auto">update</property>

<!-- 映射配置文件,需要引入映射的配置文件 -->
<mapping resource="domain/User.hbm.xml"/>

</session-factory>

4.demo1测试类,hibernate入门存储数据

package dao;

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

import domain.user;

public class demo1 {
public static void main(String[] args) {
//读取配置文件
Configuration conf= new Configuration().configure();
//创建sessionFactory工厂
SessionFactory sf=conf.buildSessionFactory();
//打开session
Session session=sf.openSession();
//创建事务
Transaction tx=null;

tx=session.beginTransaction();//开始
//持久化
  try{
user u=new user();
u.setUsername("xu");
u.setPassword("123");
session.save(u);
tx.commit();
  }catch(Exception e){
  if(tx!=null){
  tx.rollback();}
  e.printStackTrace();
  }finally{
  session.close();
  }
  }

}

5.测试结果


猜你喜欢

转载自blog.csdn.net/qq_37162423/article/details/80226267