Hibernate入门

public class User {
	
	private String id;
	private String name;
	private String password;
	private Date createTime;
	private Date expireTime;

         public User(){}

         // getter and setter methods
         // .....
}

<hibernate-mapping>
	<class name="org.darkness.hibernate.User">
		<id name="id">
			<generator class="uuid"/>
		</id>
		<property name="name"/>
		<property name="password"/>
		<property name="createTime"/>
		<property name="expireTime"/>
	</class>
</hibernate-mapping>

import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;

public class ExportDB {

	public static void main(String[] args) {
		
		//读取hibernate.cfg.xml文件
		Configuration cfg = new Configuration().configure();
		
		SchemaExport export = new SchemaExport(cfg);
		
		export.create(true, true);
	}
}


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) {
		
		//读取hibernate.cfg.xml文件
		Configuration cfg = new Configuration().configure();
		
		//创建SessionFactory
		SessionFactory factory = cfg.buildSessionFactory();
		
		Session session = null;
		try {
			session = factory.openSession();
			
			//开启事务
			session.beginTransaction();
			
			User user = new User();
			user.setName("张三");
			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();
				}
			}
		}
		
	}
}


<hibernate-configuration>
	<session-factory>
		<property name="hibernate.connection.url">jdbc:mysql://localhost/hibernate_first</property>
		<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="hibernate.connection.username">root</property>
		<property name="hibernate.connection.password">depravedAngel</property>
		<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
		<property name="hibernate.show_sql">true</property>
		
		<mapping resource="org/darkness/hibernate/User.hbm.xml"/>
	</session-factory>
</hibernate-configuration>

你可能感兴趣的:(java,mysql,xml,Hibernate,jdbc)