hibernate ——helloWorld程序(annotation配置)

时间:2022-10-11 12:11:20

在  《hibernate  ——helloWorld程序(XML配置)》基础上,修改、添加部分文件;

1、Teacher类和Teacher表

package com.pt.hibernate;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table; @Entity
@Table(name="teacher")
public class Teacher {
private int id;
private String name;
private String title; @Id //加在get方法上面
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 String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
} }

Teacher.java

 CREATE TABLE `teacher` (
`id` int(20) NOT NULL,
`name` varchar(20) DEFAULT NULL,
`title` varchar(20) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

Teacher.sql

2、hibernate.cfg.xml配置文件

 <?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- Database connection settings -->
<!-- <property name="connection.driver_class">org.hsqldb.jdbcDriver</property>
<property name="connection.url">jdbc:hsqldb:hsql://localhost/TestDB</property> --> <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost/test?useUnicode=true&amp;characterEncoding=UTF-8</property>
<property name="connection.username">root</property>
<property name="connection.password"></property> <!-- SQL dialect -->
<property name="dialect">
org.hibernate.dialect.MySQLInnoDBDialect
</property>
<property name="show_sql">true</property>
<mapping resource="com/pt/hibernate/Student.xml"/>
<mapping class="com.pt.hibernate.Teacher" />
</session-factory> </hibernate-configuration>

hibernate.cfg.xml

3、测试类

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration; import com.fasterxml.classmate.AnnotationConfiguration;
import com.pt.hibernate.Student;
import com.pt.hibernate.Teacher; public class TeacherTest {
public static void main(String[] arges){
Teacher t= new Teacher();
t.setId(20111911);
t.setName("潘腾");
t.setTitle("英语~~");
Configuration cfg = new Configuration();
SessionFactory sessionFactory = cfg.configure().buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(t);
session.getTransaction().commit();
session.close();
sessionFactory.close(); }
}

TeacherTest.java