码迷,mamicode.com
首页 > Web开发 > 详细

hibernate(二)annotation第一个示例

时间:2015-12-11 23:58:22      阅读:305      评论:0      收藏:0      [点我收藏+]

标签:

一、在数据库中创建teacher表(数据库hibernate)

create table teache(
id int auto_increment primary key,
name varchar(20),
title varchar(20)
);

 

二、创建model

在cn.orlion.hibernate.model下创建实体类Teacher(注意添加注解,一开始只添加了@Id,然后抛出异常,后来又加上了@GeneratedValue(strategy = GenerationType.AUTO))

package cn.orlion.hibernate.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Teacher{

    private int id;
    
    private String name;
    
    private String title;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    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;
    }
}

 

三、在配置文件中配置类:

在hibernate.cfg.xml中添加下面一行

<mapping class="cn.orlion.hibernate.model.Teacher" />

 

OK,配置完成写一个测试:

package cn.orlion.test;

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

import cn.orlion.hibernate.model.Teacher;

public class TeacherTest {
    
    public static void main(String[] args){
        
        Teacher t = new Teacher();
        
        t.setName("test1");
        t.setTitle("title1");
        
        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();
    }
}

 

运行可以看到数据库中添加了一条记录。

技术分享

hibernate(二)annotation第一个示例

标签:

原文地址:http://www.cnblogs.com/orlion/p/5040438.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!