这里的目标是建立环境,开发一个小程序,看看运行结果.
一建立web project.
把hibernate的jar文件复制到lib目录中,还有用到的支持jar文件哦.还有JDBC驱动.
二开发第一个hibernate程序.
这时用要建立一个hibernate.cfg.xml的配置文件.看看里面是什么?
<!DOCTYPEhibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<propertyname="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<propertyname="hibernate.connection.url">jdbc:mysql:///test</property>
<propertyname="hibernate.connection.username">root</property>
<propertyname="hibernate.connection.password">XXX</property>
<propertyname="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
前面五句是mySQL连接必须的信息,用户名,密码,那个数据库,用到的JDBC驱动哦,这几个内容那来的,可以参考hibernate框架中的ETC目录下hibernate.properties文件,里面对应了很多.
<propertyname="hibernate.hbm2ddl.auto">create</property>//这句要重点注意,用什么方式访问
<propertyname="show_sql">true</property>//显示SQL语句.
<mappingresource="com/liyu/hibernate/domain/User.hbm.xml"/>映射的对象文件,不知我的叫法对不对
</session-factory>
</hibernate-configuration>
上面映射了文件是什么呢?
就是持久化对象的属性所对应数据库存中的字段,我看主要就是为了指白这个东西.不知这样的说法,大家理解不?
看例子User.hbm.xml:
<?xmlversion="1.0"?>
<!DOCTYPEhibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mappingpackage="com.liyu.hibernate.domain">
<classname="User">
<idname="id">
<generatorclass="native"></generator>
</id>
<propertyname="name"/>
<propertyname="birthday"/>
</class>
</hibernate-mapping>
再看看那个对象User.java,就是个javaBean对象:
package com.liyu.hibernate.domain;
import java.util.Date;
public class User {
private Integerid;
private Stringname;
private Datebirthday;
public Integer getId() {
returnid;
}
public void setId(Integer id) {
this.id = id;
}
public StringgetName() {
returnname;
}
public void setName(String name) {
this.name = name;
}
public Date getBirthday() {
returnbirthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
}
没什么牛气吧!
看看写的测试类:
package com.liyu.hibernate;
import java.util.Date;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import com.liyu.hibernate.domain.User;
public class TestHibernate {
public static void main(String[] args){
Configuration cfg=new Configuration();
cfg.configure();
SessionFactory sf=cfg.buildSessionFactory();
Session s=sf.openSession();
Transaction tx=s.beginTransaction();
User user=new User();
user.setBirthday(new Date());
user.setName("name");
s.save(user);
tx.commit();
s.close();
System.out.println("save OK!");
}
}
输出为:
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
Hibernate: insert into User (name, birthday) values (?, ?)
save OK!
前面加了
<property name="hibernate.hbm2ddl.auto">create</property>
数据库中都不需要建立表,hibernate直接自动帮我们建立好,这个属性有那些,请看hibernate框架中的ETC目录下hibernate.properties文件.