hibernate 建立annotation版本的helloworld

来源:互联网 发布:godaddy购买域名教程 编辑:程序博客网 时间:2024/06/10 19:23

1、添加annotation相应的jar包。

2.Teacher.java

package com.wxh.hibernate.model;import javax.persistence.Entity; import javax.persistence.Id;@Entitypublic class Teacher {private int id;private String name;private String title;@Idpublic int getId() {return id;}@Idpublic 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;}}

3.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">com.mysql.jdbc.Driver</property>        <property name="connection.url">jdbc:mysql://localhost/db</property>        <property name="connection.username">root</property>        <property name="connection.password">111</property>                <!-- SQL dialect -->        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>                <!-- Disable the second-level cache  -->        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>        <!-- Echo all executed SQL to stdout -->        <property name="show_sql">true</property>       <mapping class="com.wxh.hibernate.model.Teacher"/>    </session-factory></hibernate-configuration>


4.TeacherTest.java

import org.hibernate.Session; import org.hibernate.SessionFactory;import org.hibernate.cfg.AnnotationConfiguration;import org.hibernate.cfg.Configuration;import com.wxh.hibernate.model.Student;import com.wxh.hibernate.model.Teacher;public class TeacherTest {public static void main(String[] args){Teacher t=new Teacher();t.setId(1);t.setName("t1");t.setTitle("中级");Configuration cfg=new AnnotationConfiguration();SessionFactory sf=cfg.configure().buildSessionFactory();Session session=sf.openSession();session.beginTransaction();session.save(t);session.getTransaction().commit();session.close();sf.close();}}



0 0
原创粉丝点击