hibernate入门
新建一 java 项目
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory > <!-- mysql数据库驱动 --> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <!-- mysql数据库名称 --> <property name="hibernate.connection.url">jdbc:mysql://10.170.0.47:3306/test</property> <!-- 数据库的登陆用户名 --> <property name="hibernate.connection.username">root</property> <!-- 数据库的登陆密码 --> <property name="hibernate.connection.password">root</property> <!-- 方言:为每一种数据库提供适配器,方便转换 --> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <mapping resource="com/example/hibernate/User.hbm.xml"/> </session-factory> </hibernate-configuration>
配之为上
public class User {
private String id;
private String username;
private String password;
private Date createTime;
private Date expireTime;
这是 user 类
<?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.example.hibernate.User"> <id name="id"> <generator class="uuid"/> </id> <property name="username"/> <property name="password"/> <property name="createTime"/> <property name="expireTime"/> </class> </hibernate-mapping>
配置 User.hbm.xml
package com.example.hibernate; import org.hibernate.tool.hbm2ddl.SchemaExport; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class ExportDB { public static void main(String[] args) { // TODO Auto-generated method stub //默认读取hibernate.cfg.xml文件 Configuration cfr = new Configuration().configure(); SchemaExport export = new SchemaExport(cfr); export.create(true, true); } }
生成表 Java类
package com.example.hibernate; import java.util.Date; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class Client { public static void main(String[] args) { //读取配置文件 Configuration cfg = new Configuration().configure(); SessionFactory factory = cfg.buildSessionFactory(); Session session = null; try{ session = factory.openSession(); //开启事务 session.beginTransaction(); User user = new User(); user.setUsername("用户名"); user.setPassword("123"); user.setCreateTime(new Date()); user.setExpireTime(new Date()); session.save(user); //提交事务 session.getTransaction().commit(); }catch(Exception e){ e.printStackTrace(); //回滚事务 session.getTransaction().rollback(); }finally{ if(session != null){ if(session.isOpen()){ //关闭session session.close(); } } } } }
测试 main cls
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。