在学习Hibernate
有个car的数据库,只有一个表basiccar
四个字段:
id,name,factory,date
我编写了POJO文件,也映射了,也写了Hibernate配置文件
POJO:
- Java code
package basicCar.bean;import java.util.Date;public class BasicCar implements java.io.Serializable{ private long id; private String name; private String factory; private Date date; public BasicCar(){ } public BasicCar(String name,String factory,Date date){ this.name = name; this.factory = factory; this.date = date; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getFactory() { return factory; } public void setFactory(String factory) { this.factory = factory; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } }
映射文件:
- XML code
<hibernate-mapping><class name="basicCar.bean.BasicCar" table="basiccar"> <id name="id" type="long" column="id" > <generator class="increment" /> </id> <property name="name" type="java.lang.String" column="name" /> <property name="factory" type="java.lang.String" column="factory" /> <property name="date" type="date" column="date" /> </class></hibernate-mapping>
Hibernate;
- XML code
<hibernate-configuration> <session-factory> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.username">root</property> <property name="connection.password">1119</property> <property name="connection.url">jdbc:mysql://localhost:3306/car</property> <property name="show_sql">true</property> <mapping resource="basicCar/bean/BasicCar.hbm.xml" /> </session-factory></hibernate-configuration>
util:
- Java code
package com.chuanjie56.util;import org.hibernate.HibernateException;import org.hibernate.Session;import org.hibernate.cfg.Configuration;public class HibernateSessionFactory { private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml"; @SuppressWarnings("unchecked") private static final ThreadLocal threadLocal = new ThreadLocal(); private static final Configuration cfg = new Configuration(); private static org.hibernate.SessionFactory sessionFactory; @SuppressWarnings("unchecked") public static Session currentSession() throws HibernateException { Session session = (Session) threadLocal.get(); if (session == null) { if (sessionFactory == null) { try { cfg.configure(CONFIG_FILE_LOCATION); sessionFactory = cfg.buildSessionFactory(); } catch (Exception e) { System.err.println("%%%% Error Creating SessionFactory %%%%"); e.printStackTrace(); } } session = sessionFactory.openSession(); threadLocal.set(session); } return session; } @SuppressWarnings("unchecked") public static void closeSession() throws HibernateException { Session session = (Session) threadLocal.get(); threadLocal.set(null); if (table>