Hibernate连接MySQL
时间:2021-07-01 10:21:17
帮助过:48人阅读
- <!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:
- </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
[java] view plain
copy
- 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
[java] view plain
copy
- <?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
[java] view plain
copy
- package com.abc;
-
- import org.hibernate.*;
- import org.hibernate.cfg.*;
-
- public class Test {
- public static void main(String[] args) {
- try {
-
- SessionFactory sf = new Configuration().configure().buildSessionFactory();
-
- Session session = sf.openSession();
-
- Transaction tx = session.beginTransaction();
-
- Student stu = new 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中查询数据
Hibernate连接MySQL
标签:显示 use title char main lib sig ace except