您的位置:首页 > 其它

SS3.2_Hibernate_Annotation 使用Annotation注解实现的Hibernate范例

2017-02-06 16:06 489 查看
SS3.1_Hibernate_ByMyEclipse (XML)
SS3.2_Hibernate_Annotation (Annotation)



SS3.2_Hibernate_Annotation项目由项目SS3.1_Hibernate_ByMyEclipse拷贝而来,项目结构截图如下:



使用AnnotationConfiguration创建config对象(注意红色字体标识):

package net.nw.dao;

import org.hibernate.Session;

import org.hibernate.SessionFactory;

import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;

import net.nw.vo.Student;

public class HibernateTest {
public static void main(String[] args) {
SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
try{
Student s = new Student();
s.setSname("zhangsan");
session.save(s);
tx.commit();
}catch(Exception ex){
tx.rollback();
ex.printStackTrace();
}finally{
if(session !=null){
session.close();
}
}
}

}

@Entity          ------[b]加在Class类上面                          import javax.persistence.Entity;

@Id              ------ 一般加在getter方法上面            import javax.persistence.Id;

@GeneratedValue      ------ 一般加在主键get属性方法上    import javax.persistence.GeneratedValue;[/b]

package net.nw.vo;
import javax.persistence.Entity;

import javax.persistence.GeneratedValue;

import javax.persistence.GenerationType;

import javax.persistence.Id;

@Entity

public class Student {
private int sid;
private String sname;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)

public int getSid() {
return sid;
}
public void setSid(int sid) {
this.sid = sid;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}

}

在hibernate.cfg.xml中注册实体类<mapping class="net.nw.vo.Student"/>(注意红色字体标识):

<?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">

<!-- Generated by MyEclipse Hibernate Tools.                   -->

<hibernate-configuration>

    <session-factory>

   <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
 <property name="connection.url">jdbc:mysql://localhost:3306/testdb</property>
 <property name="connection.username">root</property>
 <property name="connection.password">123456</property>
 <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
 <property name="show_sql">true</property>
 <property name="hbm2ddl.auto">create</property>
 <property name="current_session_context_class">thread</property>
 <mapping class="net.nw.vo.Student"/>

    </session-factory>

</hibernate-configuration>

测试运行效果截图如下:




内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐