hibernate mysql_Hibernate连接MySQL

1 下载hibernate-3.6.0 Final.zip到任意目录,解压缩后得到hibernate目录

2 下载slf4j-1.7.13.zip到任意目录,解压缩后得到slf4j-1.7.13

3 在test库中创建student表

msql -localhost -u root –p

use test

create table student(NO char(20),name varchar(20),primarykey(NO));

4 创建一个名为HibernateDemo的JavaProject

5 添加包

添加hibernate\jar中的所有包

添加slf4j-1.7.13中的slf4j-nop-1.7.13.jar

添加MySQL的驱动程序mysql-connector-Java-5.1.38-bin.jar

1913532648f66f7716cfe8a557218856.png

6添加两个配置文件和两个类

Hibernate.cfg.xml

Student.java

Student.hbm.xml

Test.java

05db2c46568497d7d0f1b9092c027a46.png

(1)在src目录下添加目录下添加hibernate.cfg.xml

hibernate-configuration PUBLIC

"-//Hibernate/Hibernate Configuration DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

true

org.hibernate.dialect.MySQLInnoDBDialect

com.mysql.jdbc.Driver

jdbc:mysql://localhost:3306/test

root

123456

(2)在src目录下的com.abc包中添加Student.java

package com.abc;

public class Student {

private String NO;

private String name;

public String getNO() {

return NO;

}

public void setNO(String NO) {

this.NO = NO;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

}

(3)在src目录下添加Student.hbm.xml

hibernate-mapping

PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

(4)Test.java

package com.abc;

import org.hibernate.*;

import org.hibernate.cfg.*;

public class Test {

public static void main(String[] args) {

try {

//通过Configuration获得一个SessionFactory对象

SessionFactory sf = new Configuration().configure().buildSessionFactory();

//打开一个Session

Session session = sf.openSession();

//开始一个事务

Transaction tx = session.beginTransaction();

//创建一个Student对象

Student stu = new Student();

//通过session的save()方法将Student对象保存到数据库中

stu.setNO("2016003");

stu.setName("Zhang San");

session.save(stu);

//提交事务

tx.commit();

//关闭会话

session.close();

} catch(Exception e) {

e.printStackTrace();

}

}

}

7 验证

(1)运行Test.java,结果为

Hibernate: insert into Student (name, NO)values (?, ?)

(2)从MySQL中查询数据

818aa976db4871d081552906fb0c4426.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值