千家信息网

hibernate第一个例子-保存对象

发表于:2024-10-25 作者:千家信息网编辑
千家信息网最后更新 2024年10月25日,3.hibernate第一个例子-保存对象使用hibernate框架需要导入的jar包:antlr-2.7.6backport-util-concurrentc3p0-0.9.1commons-col
千家信息网最后更新 2024年10月25日hibernate第一个例子-保存对象

3.hibernate第一个例子-保存对象

使用hibernate框架需要导入的jar包:

antlr-2.7.6

backport-util-concurrent

c3p0-0.9.1

commons-collections-3.1 apache集合帮助的包

commons-logging-1.1.1日志

dom4j-1.6.1解析XML

ehcache-1.5.0缓存框架

hibernate3hibernate核心包

javassist-3.9.0.GA代理模式工具包,解决懒加载问题

jta-1.1

log4j日志

mysql-connector-java-5.1.10-bin数据库连接

slf4j-api-1.5.8

slf4j-log4j12


Person-持久化类

/** * 对象的序列化的作用:让对象在网络上传输,以二进制的形式传输 * Serializable标示接口 */public class Person implements Serializable{    private Long pid;    private String pname;    private String psex;    set,get方法}


映射文件 Person.hbm.xml

                                                                                    


配置文件 hibernate.cfg.xml

                        root                root                            jdbc:mysql://localhost:3306/hibernateDay01                            update                    true             

测试

import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.Transaction;import org.hibernate.cfg.Configuration;import org.junit.Test; public class PersonTest {    @Test    public void testCreateTable(){ //测试数据库中会不会根据持久化类和映射文件生成表        Configuration configuration = new Configuration();        configuration.configure();  //加载配置文件1、该配置文件必须放在classpath下2、名称必须为hibernate.cfg.xml        configuration.buildSessionFactory();        }    @Test    public void testSavePerson(){        Configuration configuration = new Configuration();        configuration.configure();          SessionFactory factory = configuration.buildSessionFactory();                Session session = factory.openSession();        Transaction transaction = session.beginTransaction();                Person person = new Person();        person.setPname("班长2");        person.setPsex("女");                /**         * 参数必须持久化对象         */        session.save(person);                transaction.commit();        session.close();    }}


0