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的Java Project
5 添加包
添加hibernate\jar中的所有包
添加slf4j-1.7.13中的slf4j-nop-1.7.13.jar
添加MySQL的驱动程序mysql-connector-Java-5.1.38-bin.jar
6添加两个配置文件和两个类
Hibernate.cfg.xml
Student.java
Student.hbm.xml
Test.java
(1)在src目录下添加目录下添加hibernate.cfg.xml
- <!DOCTYPE hibernate-configuration PUBLIC
- "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
- "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
- <hibernate-configuration>
- <session-factory>
- <!--程序执行的时候是否显示真正的sql语句-->
- <property name="show_sql">true</property>
- <!--使用的SQL对应的“方言”,此处是Oracle11的“方言”-->
- <property name="dialect">org.hibernate.dialect.MySQLInnoDBDialect
- </property>
- <!--连接数据库的Driver-->
- <property name="connection.driver_class">
- com.mysql.jdbc.Driver
- </property>
- <!--数据库连接url-->
- <property name="connection.url">
- jdbc:mysql://localhost:3306/test
- </property>
- <!--用户名-->
- <property name="connection.username">root</property>
- <!--密码-->
- <property name="connection.password">123456</property>
- <mapping resource="Student.hbm.xml"/>
- </session-factory>
- </hibernate-configuration>
(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
- <?xml version="1.0" encoding="utf-8"?>
- <!DOCTYPE hibernate-mapping
- PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
- "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
- <hibernate-mapping package="com.abc">
- <class name="Student" table="Student">
- <id name="NO">
- <generator class="assigned" />
- </id>
- <property name="name" column="name" type="java.lang.String" />
- </class>
- </hibernate-mapping>
(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中查询数据
学习时的痛苦是暂时的 未学到的痛苦是终生的