POJO对象:
public class Person {
public Integer id;
public String name;
public Date birthday;
public int password;
public Person(){}
public Person(String name, Date birthday, int password) {
super();
this.name = name;
this.birthday = birthday;
this.password = password;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public int getPassword() {
return password;
}
public void setPassword(int password) {
this.password = password;
}
@Override
public String toString() {
return "Person [id=" + id + ", name=" + name + ", birthday=" + birthday
+ ", password=" + password + "]";
}
}
对象与表映射文件
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping SYSTEM "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd" >
<!-- 持久化映射 (将Java对象映射到数据库表-->
<hibernate-mapping>
<class name="helloworld.Person" table="t_person">
<id name="id">
<generator class="native"></generator>
</id>
<property name="name"></property>
<property name="password"></property>
<property name="birthday"></property>
</class>
</hibernate-mapping>
hibernate配置文件,放在根目录下:
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql:///hibernate_db</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">199151</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="hibernate.show_sql">true</property>
<property name="bibernate.format_sql">true</property>
<mapping resource="helloworld\Person.hbm.xml"/>
</session-factory>
</hibernate-configuration>
注意:此处没有配置dialect属性,根据MySQL的版本而定,我用的为最新版本的MySQL,如果配置了dialect属性,自动创建表失败,如果是老版本的额MySQL,则必须有dialect属性。
测试test类:
package hibernateTest;
import helloworld.Person;
import java.util.Date;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class HIbernateTest {
public static void main(String []args){
Configuration config = new Configuration().configure();
SessionFactory factory = config.buildSessionFactory();
Session session = factory.openSession();
Transaction tx = session.beginTransaction();
Person p = new Person("admin",new Date(),123456);
session.save(p);
tx.commit();
session.close();
factory.close();
}
}