hibernate学习3_简单hibernate_Annotation实现

一、工程搭建 (需要注意额外引入如下三个jar包)

 

技术分享

 

二、构建实体类,添加上对应Annotation注解

技术分享
package com.djl.test;

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Teacher {
    @Id
    private int id;
    private String name;
    private int age;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    
}
View Code

三、hiberinate初始化配置文件

技术分享
<?xml version=‘1.0‘ encoding=‘utf-8‘?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
        
<hibernate-configuration>
    <session-factory>
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/hibernate?characterEncoding=UTF-8</property>
        <property name="connection.username">root</property>
        <property name="connection.password">123456</property>
        <property name="connection.pool_size">1</property>
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="show_sql">true</property>
<!--         <mapping resource="com/djl/test/student.hbm.xml"/> -->
        <mapping class="com.djl.test.Teacher"/>
    </session-factory>
</hibernate-configuration>
View Code

 注意此时引入的不是实体类对应的映射xml配置文件,直接是引入注解后的类

四、主程序测试

技术分享
package com.djl.test;

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

public class MainTest {
    public static void main(String... args){
        Teacher teacher = new Teacher();
        teacher.setId(0);
        teacher.setAge(30);
        teacher.setName("wanghan");
        Configuration config = new AnnotationConfiguration();
        config.configure();
        SessionFactory factory =  config.buildSessionFactory();
        Session session = factory.openSession();
        session.beginTransaction(); 
        session.save(teacher);
        session.getTransaction().commit();
        session.close();
        factory.close();        
    }
}
View Code

注意此时ConfigurManager中初始化用到的类为AnnotationConfiguration

 

测试结果:

技术分享

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。