hibernate向MySQL里面添加数据表和数据

本文详细介绍了如何使用Hibernate搭建一个Java项目,包括项目的整体结构、实体类定义、配置文件设置等关键步骤,并通过JUnit测试保存数据到MySQL数据库。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.新建一个java project项目,里面加入hibernate、Junit、MySQL要用的jar包,然后新建一个source folder取名为test,在src和test里面加入相应的文件。整体的框架图如下图所示:


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

import java.util.Date;

public class Studens {

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

	public Studens() {

	}

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

	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 getAddress() {
		return address;
	}

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

	@Override
	public String toString() {
		return "Studens [sid=" + sid + ", sname=" + sname + ", gender="
				+ gender + ", birthday=" + birthday + ", address=" + address
				+ "]";
	}

}

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>
		<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="connection.url">jdbc:mysql://localhost:3306/hibernate?characterEncoding=utf-8</property>
		<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
		<property name="connection.username">root</property>
		<property name="connection.password">root</property>

		<property name="show_sql">true</property>
		<property name="format_sql">true</property>
		<property name="hbm2ddl.auto">create</property>

		<mapping resource="Studens.hbm.xml" />
	</session-factory>
</hibernate-configuration>

4.Studens.hbm.xml里面的代码如下所示(这个是新建hbm.xml文件时自动生成的代码,无需修改):
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 2017-10-2 11:14:07 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
    <class name="Studens" table="STUDENS">
        <id name="sid" type="int">
            <column name="SID" />
            <generator class="assigned" />
        </id>
        <property name="sname" type="java.lang.String">
            <column name="SNAME" />
        </property>
        <property name="gender" type="java.lang.String">
            <column name="GENDER" />
        </property>
        <property name="birthday" type="java.util.Date">
            <column name="BIRTHDAY" />
        </property>
        <property name="address" type="java.lang.String">
            <column name="ADDRESS" />
        </property>
    </class>
</hibernate-mapping>

5.Eclipse里面StudensTest.java里面的代码如下所示:

import java.util.Date;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class StudensTest {

	private SessionFactory sessionFactory;
	private Session session;
	private Transaction transaction;

	@Before
	public void init() {
		Configuration config = new Configuration().configure();
		ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
				.applySettings(config.getProperties()).buildServiceRegistry();
		sessionFactory = config.buildSessionFactory(serviceRegistry);
		session = sessionFactory.openSession();
		transaction = session.beginTransaction();
	}

	@After
	public void destory() {
		transaction.commit();
		session.close();
		sessionFactory.close();
	}

	@Test
	public void testSaveStudens() {
		Studens s = new Studens(1, "张三丰", "男", new Date(), "武当山");
		session.save(s);
	}

}


MyEclipse里面StudensTest.java代码(students写成了studens,不合的地方改过来):

package test;

import java.util.Date;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.service.ServiceRegistry;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import entity.Students;

public class StudensTest {
	private SessionFactory sessionFactory;
	private Session session;
	private Transaction transaction;

	@Before
	public void init() {
		// 创建服务注册对象
		ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().configure().build();
		// 创建会话工厂对象
		sessionFactory = new MetadataSources(serviceRegistry).buildMetadata().buildSessionFactory();
		// 会话对象
		session = sessionFactory.openSession();
		// 开启事物
		transaction = session.beginTransaction();
	}

	@After
	public void destory() {
		// 提交事物
		transaction.commit();
		// 关闭会话
		session.close();
		// 关闭会话工厂
		sessionFactory.close();
	}

	@Test
	public void testSaveStudents() {
		// 生成学生对象
		Students student = new Students(1, "张三丰", "男", new Date(), "武当山");
		System.out.println(student);
		session.save(student);
		System.out.println(session);
	}

}

6.新建一个数据库,数据库的名字与上面 的数据库的名字要一致。



7.运行Junit里面 的testSaveStudens类,然后打开数据库刷新,可以看到数据库里面自动新建了一张数据表,并且里面自动添加了一项数据。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值