第一步:
导包:(这是我根据其他网站的介绍导入的包,可能不完善,但开发没什么问题,遇到问题再说)
当然还有mysql的jar包
第二步:进行hibernate环境配置
在classpath目录下建立hibernate.cfg.xml配置文件,名字最好不要修改:
内容:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- Database connection settings --> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://localhost:3306/student?serverTimezone=UTC</property> <property name="connection.username">root</property> <property name="connection.password">123456</property> <!-- JDBC connection pool (use the built-in) --> <!-- <property name="connection.pool_size">1</property> --> <!-- SQL dialect 方言 MySQLDialect不同数据库不一样--> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <!-- Enable Hibernate's automatic session context management --> <!-- <property name="current_session_context_class">thread</property> --> <!-- Disable the second-level cache --> <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property> <!-- Echo all executed SQL to stdout 生产的sql打印出来--> <property name="show_sql">true</property>
<mapping resource="com/xxc/model/Student.hbm.xml"></mapping><!--后面的映射配置文件--> </session-factory> </hibernate-configuration>
第三步,创建数据库
如果对数据库创建有问题的自行百度。
第四步:
建立实体类:Student.java
package com.xxc.model; public class Student { private int id; private String name; private int age; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
实体类映射配置文件:Student.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"> <hibernate-mapping> <class name="com.xxc.model.Student" table="student"><!-- 表名 --> <id name="id"></id><!-- column对应数据库表里面的字段 --> <property name="name" ></property> <property name="age" ></property> </class> </hibernate-mapping>
第五步,建立执行程序:Test1.java
package hibernateTest; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import com.xxc.model.Student; public class Test1 { public static void main(String[] args) { Student s = new Student(); s.setId(5); s.setName("xxkjlc"); s.setAge(45); Configuration cfg = new Configuration(); SessionFactory sf = cfg.configure().buildSessionFactory(); Session session = sf.openSession(); //开始事务 session.beginTransaction(); session.save(s); //结束事务 session.getTransaction().commit(); session.close(); sf.close(); } }
结果:
在控制台中会输出:
数据库中也会存入数据: