Hibernate中的@Entity注解

1.新建一个java project项目,里面新建一个lib文件夹,lib文件夹里面放置要用的一些jar文件,然后全部选中导入到项目中去。整体的框架如下图所示:

Hibernate中的@Entity注解_第1张图片


2.Students.java里面的代码如下图所示:

package entity;

import java.util.Date;

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity(name = "t_students")
public class Students {

	private int sid;
	private String sname;
	private String gender;
	private Date birthday;
	private String major;
	private String address;

	public Students() {

	}

	public Students(int sid, String sname, String gender, Date birthday,
			String major, String address) {
		this.sid = sid;
		this.sname = sname;
		this.gender = gender;
		this.birthday = birthday;
		this.major = major;
		this.address = address;
	}

	@Id
	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;
	}

	public String getGender() {
		return gender;
	}

	public void setGender(String gender) {
		this.gender = gender;
	}

	public Date getBirthday() {
		return birthday;
	}

	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}

	public String getMajor() {
		return major;
	}

	public void setMajor(String major) {
		this.major = major;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

}

3.hibernate.cfg.xml里面的代码如下图所示:




	
		com.mysql.jdbc.Driver
		jdbc:mysql://localhost:3306/hibernate?characterEncoding=utf-8
		org.hibernate.dialect.MySQLDialect
		root
		root
		true
		true
		create
		thread

		
	


4.TestStudents.java里面的代码如下图所示:

package entity;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.junit.Test;

public class TestStudents {

	@Test
	public void testShemaExport() {
		Configuration config = new Configuration().configure();
		ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
				.applySettings(config.getProperties()).buildServiceRegistry();
		SessionFactory sessionFactory = config
				.buildSessionFactory(serviceRegistry);
		SchemaExport export = new SchemaExport(config);
		export.create(true, true);
	}

}

5.在Navicat数据库里面新建一个数据库,数据库的名称要与上面 的数据库的名称相同。

Hibernate中的@Entity注解_第2张图片


6.运行testShemaExport类,数据库里面会自动创建一张表。

Hibernate中的@Entity注解_第3张图片

你可能感兴趣的:(Hibernate中的@Entity注解)