hibernate中简单的增删改查

项目的整体结构如下

 

1.配置文件

hibernate.cfg.xml

<!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="connection.url">jdbc:mysql://127.0.0.1:3306/diban</property>
  <property name="connection.user">root</property>
  <property name="connection.password">root</property>
  <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
  <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
  <!-- 将当前会话和线程绑定 -->
  <property name="current_session_context_class">thread</property>
  <property name="show_sql">true</property>
  <property name="format_sql">true</property>

  <!-- 在配置文件中引入映射文件 -->
  <mapping resource="cn/test/entity/product.hbm.xml"/>
</session-factory>
</hibernate-configuration>

 

2.映射文件

<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
  <class name="cn.test.entity.Product" table="`product`">
     <id name="id" type="java.lang.Integer" column="`id`">
      <generator class="assigned"></generator><!-- 由应用程序生成,即自己在程序中书写 -->
    </id>
    <property name="productName" type="java.lang.String" column="`product_name`"></property>
    <property name="productInfo" type="java.lang.String" column="product_info"></property>
    <property name="isno" type="java.lang.Integer" column="isno"></property>
    <property name="productType" type="java.lang.Integer" column="product_type"></property>
    <property name="productYuanjia" type="java.lang.Double" column="product_yuanjia "></property>
    <property name="productPrice" type="java.lang.Double" column="product_price"></property>
    <property name="productXinghao" type="java.lang.String" column="product_xinghao"></property>
    <property name="guige" type="java.lang.String" column="guige"></property>
  </class>
</hibernate-mapping>

3.实体类

4.例子

package cn.test.test;

 

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.Test;

import cn.test.entity.Product;

public class Test001 {
/**
* 新增
*/
@Test
public void Test002() {
  Transaction tx = null;
  try {
    //1.读取并解析配置文件和映射文件
    Configuration conf = new Configuration().configure();
    //2.根据配置文件和映射文件中的信息,创建sessionFactory对象
    SessionFactory factory = conf.buildSessionFactory();
    //3.创建session对象
    Session session = factory.openSession();
    //4.开始一个事务(创建一个事物对象)
    tx = session.beginTransaction();
    //5.创建一个对象并且初始化
    Product p = new Product();
    p.setId(137);
    p.setProductName("137");
    //6.数据库操作使用sava方法将数据添加到数据库中
    session.save(p);
    //7.结束事物
    tx.commit();
  } catch (Exception e) {
    e.printStackTrace();
    //7.结束事物
    if(tx != null)
      tx.rollback();
  }
}

/**
* 删除
*/
@Test
public void Test005() {
  Transaction tx = null;
  try {
    Configuration conf = new Configuration().configure();
    SessionFactory factory = conf.buildSessionFactory();
    Session session = factory.openSession();
    tx = session.beginTransaction();
    Product p = new Product();
    p.setId(138);
    session.delete(p);
    tx.commit();
  } catch (Exception e) {
    e.printStackTrace();
    if(tx != null)
      tx.rollback();
  }
}

/**
* updata更新的方法
* saveOrUpdata
* 先根据Id到数据库中判断是否有这条数据
* 如果有那么执行更新的方法
* 如果没有那么执行增加的方法
*/
@Test
public void Test004() {
  Transaction tx = null;
  try {
    Configuration conf = new Configuration().configure();
    SessionFactory factory = conf.buildSessionFactory();
    Session session = factory.openSession();
    tx = session.beginTransaction();
    Product p = new Product();
    p.setId(138);
    p.setProductName("nimei111");
    session.saveOrUpdate(p);
    tx.commit();
  } catch (Exception e) {
    e.printStackTrace();
    if(tx != null)
      tx.rollback();
  }
}

/**
* 根据Id查询具体的某一条数据
* load 延迟加载
* 使用load方法时不会直接发动sql语句到数据库中查询具体的数据,而是会先得到一个只有id属性的代理对象,只有当使用到其他属性时才会发送
* sql语句到数据库中查询具体的数据
* get 不延迟加载
*/
@Test
public void Test003() {
  Transaction tx = null;
  try {
    //1.读取并解析配置文件和映射文件
    Configuration conf = new Configuration().configure();
    //2.根据配置文件和映射文件的信息创建会话工厂
    SessionFactory factory = conf.buildSessionFactory();
    //3.通过会话工厂打开session对象
    Session session = factory.openSession();
    //4.通过session对象创建事物对象
    tx = session.beginTransaction();
    //5.根据对象Id查询指定的单条对象数据
    //Product p = (Product) session.load(Product.class, 137);
    Product p = (Product)session.get(Product.class, 137);
    System.out.println(p.getId());
    tx.commit();
  } catch (Exception e) {
    e.printStackTrace();
    if(tx != null)
      tx.rollback();
  }
}

/**
* ------------hql
*
* 查询语法
* 1.from子句
* from Product #查询所有的Product(查询所有属性)
* 2.select子句
* select Product.id from Product 查询所有Product的id(只查询id)
* 3.where
* from Product where id = 'haha'
* from Product where productName is not null
* 4.使用表达式
* from Product where lower(productName) = 'hhh'
* lower()函数用于把字符串中的每个字母改为小写
* from Product where year(createDate) = 1980
* year()函数用于获取日期字段的年份
*
*
* 如何为sql语句传入参数:
* 1.拼接字符串
* 2.参数绑定
* 1>.按位置绑定参数
* 2>.按名称绑定参数
* 3>.将数据封装到对象中绑定参数
* 如 : from Product where id = :id and productName = :name
  * Product p = new Product();
  * p.setId(11);
  * p.setProductName("hello");
  * query.setProperties(p);
*
*/

/**
* 拼接字符串
*/
@Test
public void Test006() {
  String id = "id";
  String hql = "from Product order by "+id;
  Configuration conf = new Configuration().configure();
  Session session = conf.buildSessionFactory().openSession();
  Transaction tx = session.beginTransaction();
  Query query = session.createQuery(hql);
  List<Product> proList = query.list();
  for (Product product : proList) {
    System.out.println(product.getId()+":"+product.getProductName());
  }
}

/**
* 按位置绑定参数
*/
@Test
public void Test007() {
  String hql = "from Product order by ?";
  Configuration conf = new Configuration().configure();
  Session session = conf.buildSessionFactory().openSession();
  Transaction tx = session.beginTransaction();
  Query query = session.createQuery(hql);
  query.setString(0, "id");
  List<Product> proList = query.list();
  for (Product product : proList) {
    System.out.println(product.getId()+":"+product.getProductName());
  }
}

/**
* 按名称绑定参数
*/
@Test
public void Test008() {
  String hql = "from Product order by :id";
  Configuration conf = new Configuration().configure();
  Session session = conf.buildSessionFactory().openSession();
  Transaction tx = session.beginTransaction();
  Query query = session.createQuery(hql);
  query.setString("id", "id");
  List<Product> proList = query.list();
  for (Product product : proList) {
    System.out.println(product.getId()+":"+product.getProductName());
  }
}




/**
* 分页查询
* setFirstResult((当前页-1)*页面容量)
* setmaxResults(页面容量)
*/
@Test
public void Test009() {
  String hql = "from Product order by id";
  Configuration conf = new Configuration().configure();
  Session session = conf.buildSessionFactory().openSession();
  Transaction tx = session.beginTransaction();
  Query query = session.createQuery(hql);
  query.setFirstResult((1-1)*9); //指定从第几条数据开始查询
  query.setMaxResults(9); //指定页面容量(也就是每页显示的多少条数据)
  List<Product> proList = query.list();
  for (Product product : proList) {
    System.out.println(product.getId()+":"+product.getProductName());
  }
}
}

posted @ 2019-03-05 18:24  咣咣敲代码  阅读(135)  评论(0编辑  收藏  举报