hibernate第一个程序

本文介绍了一个使用 Hibernate 进行 ORM 操作的实战案例,包括创建数据库表、编写实体类、映射文件及核心配置文件等内容,并通过单元测试验证了增删改查功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

该项目使用到的jar包


1.我使用的是mysql关系型数据库,先建立一个数据库,并且创建一个customer(客户信息)表

2.创建一个Customer实体类(持久化类)

通常持久化类的编写应嘎遵循一些规则:

1).持久化类中必须提供无参数public构造器(如果没有提供任何构造方法,虚拟机会自动提供默认构造方法,但是如果提供了其他有参数的构造方法的话

虚拟机不再提供默认构造方法,必须手动编写无参构造方法).

2).持久化类中所有属性使用private修饰,提供public的setter/getter方法

3).必须提供标识属性OID,与数据库表中逐渐对应,例如下面Customer类id属性

4).持久化类属性应尽量使用基本数据类型的包装类型,例如int换成Integer,long换成Long,目的是为了与数据库表的字段默认值null一致。(例如int是区分不开null跟0的,不赋值的int类型默认值为0)

5).持久化类不要用final修饰,使用final修饰将无法生成代理对象进行优化.

[java]  view plain  copy
  1. public class Customer {  
  2.     private Integer id;      
  3.     private String name;    
  4.     private Integer age;     
  5.     private String sex;      
  6.     private String city;     
  7.     /** 
  8.      * @return the id 
  9.      */  
  10.     public Integer getId() {  
  11.         return id;  
  12.     }  
  13.     /** 
  14.      * @param id the id to set 
  15.      */  
  16.     public void setId(Integer id) {  
  17.         this.id = id;  
  18.     }  
  19.     /** 
  20.      * @return the name 
  21.      */  
  22.     public String getName() {  
  23.         return name;  
  24.     }  
  25.     /** 
  26.      * @param name the name to set 
  27.      */  
  28.     public void setName(String name) {  
  29.         this.name = name;  
  30.     }  
  31.     /** 
  32.      * @return the age 
  33.      */  
  34.     public Integer getAge() {  
  35.         return age;  
  36.     }  
  37.     /** 
  38.      * @param age the age to set 
  39.      */  
  40.     public void setAge(Integer age) {  
  41.         this.age = age;  
  42.     }  
  43.     /** 
  44.      * @return the sex 
  45.      */  
  46.     public String getSex() {  
  47.         return sex;  
  48.     }  
  49.     /** 
  50.      * @param sex the sex to set 
  51.      */  
  52.     public void setSex(String sex) {  
  53.         this.sex = sex;  
  54.     }  
  55.     /** 
  56.      * @return the city 
  57.      */  
  58.     public String getCity() {  
  59.         return city;  
  60.     }  
  61.     /** 
  62.      * @param city the city to set 
  63.      */  
  64.     public void setCity(String city) {  
  65.         this.city = city;  
  66.     }  
  67.     //重写toString()方法  
  68.     @Override  
  69.     public String toString() {  
  70.         return "Customer [id=" + id + ", name=" + name + ", age=" + age + ", sex=" + sex + ", city=" + city + "]";  
  71.     }  
  72.       
  73.       
  74. }  

3.编写映射文件Customer.hbm.xml

  实体类Customer目前还不具备持久化操作的能力,而Hibernate需要知道实体类Customer映射到数据库 Hibernate中的哪个表,以及类中的哪个属性

  对应数据库表中的哪一个字段,这些都需要在映射文件中配置.

  在实体类Customer所在的包中,创建一个名称为Customer.hbm.xml的映射文件,在该文件中定义了实体类Customer的属性是如何映射到customer表的列上的

开始编写xml

<?xml version="1.0" encoding="UTF-8"?>
  <!DOCTYPE hibernate-mapping PUBLIC 
       "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
       "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
  <hibernate-mapping>
      <!-- name代表的是实体类名,table代表的是表名 -->
      <class name="com.hck.entity.Customer" table="customer">
          <!-- name=id代表的是customer类中属性  column=id代表的是table表中的字段 -->
          <id name="id" column="id">
             <!-- 主键生成策略 -->
             <generator class="native"/>
          </id>
          <!-- 其他属性使用property标签来映射 -->
          <property name="name" column="name" type="string"/>
          <property name="age"  column="age"  type="integer"/>
          <property name="sex"  column="sex"  type="string"/>
          <property name="city" column="city" type="string"/>
      </class>
  </hibernate-mapping>
 

4.编写核心配置文件hibernate.cfg.xml

  Hibernate的映射文件反映了持久化类和数据库表的映射信息,

  而Hibernate的配置文件则主要用来配置数据库连接以及Hibernate运行时所需要的各个属性的值.

  在项目的src目录下创建一个名称为hibernate.cfg.xml的文件

 xml的头部编写可以按下图所以查找复制

编写hibernate.cfg.xml文件

[java]  view plain  copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2.   <!DOCTYPE hibernate-configuration PUBLIC  
  3.     "-//Hibernate/Hibernate Configuration DTD 3.0//EN"  
  4.     "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">  
  5.   <hibernate-configuration>  
  6.          <session-factory>  
  7.               <!--指定方言 -->  
  8.               <property name="hibernate.dialect">  
  9.                 org.hibernate.dialect.MySQLDialect  
  10.               </property>  
  11.               <!-- 数据库驱动 -->  
  12.               <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>  
  13.               <!-- 连接数据库的url -->  
  14.               <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/tb_test</property>  
  15.               <!-- 数据库用户名 -->  
  16.               <property name="hibernate.connection.username">root</property>  
  17.               <!-- 数据库密码 -->  
  18.               <property name="hibernate.connection.password">123456</property>  
  19.               <!-- 其他配置 -->  
  20.               <!-- 格式化sql -->  
  21.               <property name="format_sql">true</property>  
  22.               <!-- 用来关联hbm配置文件 -->  
  23.               <mapping resource="com/hck/entity/Customer.hbm.xml"/>  
  24.          </session-factory>  
  25.   </hibernate-configuration>  

 5.编写单元测试类代码如下:

[java]  view plain  copy
  1. public class HibernateTestDemo {  
  2.    //定义变量  
  3.     Configuration config;  
  4.     SessionFactory sessionFactory;  
  5.     Session session;  
  6.     Transaction transaction;  
  7.     //before表示在方法执行前执行  
  8.     @Before  
  9.     public void setUp()  
  10.     {  
  11.       //1.加载hibernate.cfg.xml配置  
  12.       config=new Configuration().configure();  
  13.       //2.获取SessionFactory  
  14.       sessionFactory=config.buildSessionFactory();    
  15.      //3.获得一个session  
  16.       session=sessionFactory.openSession();  
  17.       //4.开始事务  
  18.       transaction=session.beginTransaction();  
  19.     }  
  20.     //添加操作  
  21.     @Test  
  22.     public void insert()  
  23.     {      
  24.       //5.操作  
  25.       Customer customer=new Customer();  
  26.       customer.setId(1);  
  27.       customer.setName("zhangsan");  
  28.       customer.setAge(20);  
  29.       customer.setSex("man");  
  30.       customer.setCity("广州");  
  31.       session.save(customer);  
  32.     }  
  33.     //删除操作  
  34.     @Test  
  35.      public void delete()  
  36.      {  
  37.         //先查询  
  38.         Customer customer=(Customer)session.get(Customer.class1);  
  39.         //再删除  
  40.         session.delete(customer);  
  41.      }  
  42.     //查询操作  
  43.     @Test  
  44.     public void select()  
  45.     {  
  46.         Customer customer=(Customer)session.get(Customer.class1);  
  47.         System.out.println(customer);     
  48.     }  
  49.     //更新操作  
  50.     @Test  
  51.     public void update()  
  52.     {      
  53.       Customer customer=new Customer();  
  54.       customer.setId(1);  
  55.       customer.setName("zhangsan");  
  56.       customer.setAge(20);  
  57.       customer.setSex("man");  
  58.       //修改地址为北京  
  59.       customer.setCity("北京");  
  60.       //存在就更新,不存在就执行插入操作  
  61.       session.saveOrUpdate(customer);  
  62.     }  
  63.     //After表示在方法执行结束后执行  
  64.     @After  
  65.     public void closeTransaction()  
  66.     {  
  67.       //6.提交事务  
  68.       transaction.commit();  
  69.       //7.关闭资源  
  70.       session.close();  
  71.       sessionFactory.close();  
  72.     }  
  73. }  

1)执行插入操作后,打开mysql使用select * from customer;得到的结果:

2)执行查询操作(查看控制台输出)

3.执行更新操作

4.删除操作

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值