首页 > 代码库 > hibernate学习3_简单hibernate_Annotation实现
hibernate学习3_简单hibernate_Annotation实现
一、工程搭建 (需要注意额外引入如下三个jar包)
二、构建实体类,添加上对应Annotation注解
package com.djl.test;import javax.persistence.Entity;import javax.persistence.Id;@Entitypublic 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; } }
三、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>
注意此时引入的不是实体类对应的映射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(); }}
注意此时ConfigurManager中初始化用到的类为AnnotationConfiguration
测试结果:
hibernate学习3_简单hibernate_Annotation实现
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。