hibernate session 的save,get,update,delete 方法

来源:互联网 发布:unity3d gui 编辑:程序博客网 时间:2024/05/16 13:48

这里只是介绍session的基本方法,不涉及HQL(hibernate查询),关于查询会在后几篇博客博客介绍。

1.数据源 :


2.对应的类 (Book):

package com.cd.model;public class Book {    private int id;    private String name ;    private String  author;    public Book(){}    public Book(int id, String name, String author) {        this.id = id ;        this.name = name;        this.author = author;    }    public void setId(int id) {        this.id = id;    }    public void setName(String name) {        this.name = name;    }    public String getAuthor() {        return author;    }    public void setAuthor(String author) {        this.author = author;    }    public int getId() {        return id;    }    public String getName() {        return name;    }}


3.cfg配置文档 :

<?xml version='1.0' encoding='utf-8'?><!DOCTYPE hibernate-configuration PUBLIC        "-//Hibernate/Hibernate Configuration DTD//EN"        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"><hibernate-configuration>    <session-factory>        <!--驱动用户名密码-->        <property name="connection.url">            <![CDATA[jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8]]>        </property>        <property name="connection.driver_class">com.mysql.jdbc.Driver</property><!--数据库驱动-->        <property name="connection.username">root</property><!--数据库用户名-->        <property name="connection.password">root</property><!--数据库密码-->        <!--hibernate调试配置-->        <property name="show_sql">true</property> <!--sql语句输出到控制台-->        <property name="format_sql">true</property><!--控制sql语句输出格式-->        <!--数据库脚本生成方式-->        <property name="hbm2ddl.auto">update</property><!--update 每次更新/create 每次创建新-->        <!--使用的方言-->        <property name="dialect">org.hibernate.dialect.MySQLDialect</property><!--不同的数据库方言不同-->        <!--使用getCurrentSession-->        <property name="current_session_context_class">thread</property>        <!--使用的映射表-->        <mapping resource="config/items.hbm.xml"/><!--这个配置文件里放的是数据表和对象的映射关系-->    </session-factory>    </hibernate-configuration>


4.hbm配置文档

<?xml version='1.0' encoding='utf-8'?><!DOCTYPE hibernate-mapping PUBLIC    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"><hibernate-mapping schema="test">    <class name="com.cd.model.Book" table="book" schema="test" >        <id name="id" column="id"><generator class="increment"/></id> <!--主键自动增长-->        <property name="name" column="name" not-null="true"/>        <property name="author" column="author"/>    </class></hibernate-mapping>

5.测试类 :

package com.cd.test;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.Transaction;import org.hibernate.cfg.Configuration;import org.hibernate.service.ServiceRegistry;import org.hibernate.service.ServiceRegistryBuilder;import org.junit.After;import org.junit.Before;import org.junit.Test;public class MainTest {    private Session session;    private SessionFactory sessionFactory;    private Transaction transaction;    @Before    public void init()    {        //配置对象        Configuration configuration = new Configuration().configure();        //服务注册对象        ServiceRegistry registry =                new ServiceRegistryBuilder().applySettings(configuration.getProperties())                        .buildServiceRegistry();        //会话工厂        sessionFactory = configuration.buildSessionFactory(registry);        //会话        session = sessionFactory.openSession();        //事务        transaction = session.beginTransaction();    }    @After    public void end()    {        try        {            transaction.commit();        }        catch (Exception e)        {            System.out.println(e.getMessage());        }        session.close();        sessionFactory.close();    }    @Test    public void test()    {    //session的方法测试    }}


测试save 方法 ,将测试类的test方法改为 :

    @Test    public void test()    {        Book book = new Book(1,"qwe","jsck");        session.save(book);    }
执行结果 :

 

可以看见插入成功,但是java代码里 id 是1 数据库里 id却是 5 ,这是因为我在hbm里配置的主键生成策略是increment,这样即使我在java里设置了id,也是会被忽略的。

测试get方法 :

    @Test    public void test()    {       Book book = (Book) session.get(Book.class,1);       System.out.println(book.getName()); //输出结果为 bookstore    }

测试load方法 :

    @Test    public void test()    {        Book book = (Book) session.load(Book.class,1);        System.out.println(book.getName());    }

get和load方法都可以获得对象,但是他们也有一些区别:

1.get会立即向数据库发送sql语句并且返回对象,load方法返回的是代理对象,只保存了id,当访问其他属性的时候才会执行sql。

2.查询不存在的数据时:get返回null ,load会抛异常


测试 :update方法 :

    @Test    public void test()    {        Book book = (Book) session.get(Book.class,1);        System.out.println(book.getName()); //输出结果为 bookstore        book.setName("json");        session.update(book);        Book book1 = (Book) session.get(Book.class,1);        System.out.println(book1.getName()); //输出结果为 json    }
测试delete方法 :

    @Test    public void test()    {        Book book = (Book) session.get(Book.class,1);        session.delete(book);    }





0 0
原创粉丝点击