hibernate创建表以及表的数据增删改查

5.1项目的整体框架;


5.2 Student.java

packagecom.ask.pojo;

//新建一个学生实体类;

public class Student {

private int id;

privateString name;

privateString password;

自己生成get和set方法以及其他方法;

5.2 Student.hbm.xml配置文件

<?xml version="1.0"?>

<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/HibernateMapping DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<!--Generated 2016-7-15 14:21:30 by Hibernate Tools 3.4.0.CR1-->

<hibernate-mapping>

    <!-- 配置指定的类,会自动创建表,其表名就是类名的小写,然我们也可以自己来指定表名

                     通过table=""属性就可以指定自己想要的表名

     -->

    <class name="com.ask.pojo.Student">

   <!-- id就是类中的唯一标识 自动生成id ,class=native 底层是根据不同数据库自动生成-->

     <id name="id">

       <generator class="native" />

        </id>

         <!-- name是类中的属性

            type 是指定数据库中字段的类型

            column 数据库的字段

                 如果不指定类型和字段名那么数据库中的字段是根据类中的属性类型和名字来定的

        -->

       <property name="name"></property>

        <property name="password"></property>

     </class>

</hibernate-mapping>

5.3 hibernate.cfg.xml的配置文件;

<?xml version="1.0"encoding="UTF-8"?>

<!DOCTYPE hibernate-configuration PUBLIC

     "-//Hibernate/HibernateConfiguration DTD 3.0//EN"

      "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

    <session-factory>

        <!-- 配置数据库信息 -->

        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>

        <property name="connection.url">jdbc:mysql://localhost:3306/mydb</property>

         <property name="connection.username">root</property>

        <property name="connection.password">root</property>

       

        <!-- 配置数据库方言org.hibernate.dialect.MySQL5Dialect-->

         <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>

        <!-- 配置自动创建表 -->

        <property name="hbm2ddl.auto"></property>

        <!-- 配置在控制台中打印sql -->

        <property name="show_sql">true</property>

         <!-- 配置打印的sql格式化 -->

        <property name="format_sql">true</property>

         <!-- 配置加载类映射的文件 -->

        <mapping resource="com/ask/pojo/Student.hbm.xml"/>

     </session-factory>

</hibernate-configuration>

5.4 StudentTest.java;

package com.ask.test;

import java.util.Date;

import java.util.List;

import org.hibernate.Criteria;

import org.hibernate.Query;

import org.hibernate.Session;

importorg.hibernate.SessionFactory;

import org.hibernate.Transaction;

importorg.hibernate.cfg.Configuration;

importorg.hibernate.service.ServiceRegistry;

importorg.hibernate.service.ServiceRegistryBuilder;

importorg.hibernate.tool.hbm2ddl.SchemaExport;

import org.junit.Before;

import org.junit.Test;

import com.ask.pojo.Student;

public class StudentTest {

     privateSessionFactory sessionFactory;

     Configurationcfg;

     @Before

     publicvoid setUp() throws Exception {

       //加载 hibernate.cfg.xml的配置文件的信息;

       cfg= new Configuration().configure();

       // 申请一个ServiceRegistry;

       ServiceRegistryserviceRegistry = new ServiceRegistryBuilder()

              .applySettings(cfg.getProperties()).buildServiceRegistry();

 

       //导入sessionFactory

       sessionFactory= cfg.buildSessionFactory(serviceRegistry);

     }

   @Test

     publicvoid testCreateTable() {

       Sessionsession = sessionFactory.openSession();

       Transactiontx = session.beginTransaction();

       SchemaExportschemaExport = new SchemaExport(cfg);

       schemaExport.create(true,true);

       System.out.println("Tablecreated.");

       tx.commit();

     }

   //用户的添加;

     @Test

     publicvoid testInsert() {

       Sessionsession = sessionFactory.openSession();

    Transaction tx =session.beginTransaction();

        Student s=new Student(1,"tom", "123456");

       //如果没有表,创建表。有表则添加数据;

       session.save(s);

       // 提交事物;

       tx.commit();

       // 关闭session;

       session.close();

     }

     //用的修改;

     @Test

     publicvoid testUpdate() {

       Sessionsession = sessionFactory.openSession();

     Transactiontx = session.beginTransaction();

       Students = (Student) session.get(Student.class, 1);

       s.setName("lucy");//鏇存柊鏁版嵁 flush()

       session.update(s);

       tx.commit();

       session.close();

     }

     @Test

     publicvoid testDelete() {

       Sessionsession = sessionFactory.openSession();

       Transactiontx = session.beginTransaction();

       Students = (Student) session.get(Student.class, 1);

       session.delete(s);

       tx.commit();

    session.close();

     }

  //通过用户id查询;

     @Test

     publicvoid testSelectById() {

       Sessionsession = sessionFactory.openSession();

       Students = (Student) session.get(Student.class, 11);

       System.out.println(s);

       session.close();

     }

     //通过用户id指定唯一查询;

     @Test

     publicvoid testSelectUnique() {

       Sessionsession = sessionFactory.openSession();

       Stringhql="From Student e where e.id=:id";

       Queryquery = session.createQuery(hql);

       query.setInteger("id",11);

       Students =(Student) query.uniqueResult();

       System.out.println(s);

       session.close();

     }

   //查询用户列表;

     @Test

     publicvoid testSelectList() {

       Sessionsession = sessionFactory.openSession();

       Stringhql="From Student";

       Queryquery = session.createQuery(hql);

      List<Student>students=query.list();

        for (Student student : students) {

           System.out.println(student);

       }     

       session.close();

     }

     //分页查询;

     @Test

     publicvoid testSelectPageList() {

       Sessionsession = sessionFactory.openSession();

        String hql="From Student";

        Query query = session.createQuery(hql);

       query.setFirstResult(0);

       query.setMaxResults(4);

       List<Student>students=query.list();

        for (Student student : students) {

           System.out.println(student);

       }

       session.close();

     }

     //criteria分页查询;

     @Test

     publicvoid testSelectQBCList() {

       Sessionsession = sessionFactory.openSession();

       Criteriacriteria= session.createCriteria(Student.class);

       criteria.setFirstResult(0);

       criteria.setMaxResults(3);

       List<Student>students=criteria.list();

       for(Student student : students) {

           System.out.println(student);

       }

       session.close();

     }

 

}

5.5测试类的效果如下:

5.5.1表的创建;


刷新数据库查看:


5.5.2向用户添加一条数据:

在数据库查看:


5.5.3修改用户数据:


查询数据库:


5.5.4删除用户指定的数据:

查询数据库:


5.5.5 查询根据用户ID


5.5.6 分页查询


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值