JavaEE 之 Habernate

1.Habernate

  a.定义:Hibernate是一个开放源代码的对象关系映射框架,它对JDBC进行了非常轻量级的对象封装,它将POJO(简单java对象,即javabean)与数据库表建立映射关系,是一个全自动的ORM框架

  b.ORM:对象关系映射(Object Relation Mapping)

 

 

2.使用:

  a.在SRC下建hibernate.cfg.xml

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="connection.url">
            jdbc:mysql://localhost:3306/j116
        </property>
        <property name="connection.username">root</property>
        <property name="connection.password">admin</property>
        <property name="connection.driver_class">
            com.mysql.jdbc.Driver
        </property>
        <property name="dialect">
            org.hibernate.dialect.MySQLDialect
        </property>
        <property name="show_sql">true</property>
        <property name="format_sql">true</property>
        <mapping resource="com/wode/pojo/User.hbm.xml" />
    </session-factory>
</hibernate-configuration> 

  b.建User的映射配置User.hbm.xml

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="com.wode.pojo.User" table="users">
        <id name="userId" column="user_id" type="integer">
            <generator class="native"></generator>
        </id>
        <property name="userName" column="user_name" type="string"></property>
        <property name="userPwd" column="user_pwd" type="string"></property>
        <property name="userType" column="user_type" type="int"></property>
    </class>
</hibernate-mapping>

  c.使用

        User u=new User();
        u.setUserName("test");
        u.setUserPwd("test");
        u.setUserType(1);
Configuration cfg
=new Configuration(); cfg.configure();//加载hibernateConfiguration ServiceRegistry registry=new ServiceRegistryBuilder().applySettings(cfg.getProperties()).buildServiceRegistry(); SessionFactory factory=cfg.buildSessionFactory(registry);
Session session
=factory.openSession(); Transaction tx=session.beginTransaction(); session.save(u); tx.commit(); session.close();

 

 

3.增删查改

  a.增

session.save(u);

  b.删

session.delete(u);    //需要设置User的Id

  c.查

//方法一:hql
Query query = session.createQuery("from User");
List<User> list=query.list();

//方法二:sql
Query query =session.createSQLQuery("select * from users").addEntity(User.class);
List<User> list=query.list();

//方法三:单个对象
User u=(User) session.load(User.class, 1);//延迟加载
User u=(User) session.get(User.class, 1);

  d.改

//方法一
User u = (User) session.get(User.class, 1);
u.setUserPwd("123456");
session.beginTransaction().commit();

//方法二(没set的属性将自动设为空,不建议使用)
User u = new User();
u.setUserId(1);
u.setUserPwd("123456");
session.update(u);
session.beginTransaction().commit();

 

 

4.查询拓展

  a.分页查询

        Query query = session.createQuery("from User");
        //当前页
        int currentPage = 1;
        //一页多少条
        int pageSize = 5;
        
        query.setFirstResult((currentPage-1)*pageSize);
        query.setMaxResults(pageSize);
        
        List<User> list = query.list();
        for(User u : list){
            System.out.println(u.getUserName()+" "+u.getUserPwd());
        }

  b.聚合函数

Query query=session.createQuery("select count(*) from Course");

  c.模糊查询

//Query query = session.createQuery("from User u where u.userName like ?");
//query.setString(0, "%z%");
Query query = session.createQuery("from User u where u.userName like :name");
query.setString("name", "%z%");
List<User> list = query.list();

  d.不用session的方式

Query query=session.createQuery("delete  Course c where c.courseName =wa ");
int =query.executeUpdate()

 

 

5.一对多

  a.在Many方xml中配置 

<many-to-one name="dept" class="com.wode.entity.Dept" column="deptNo" lazy="false" fetch="join"/>

  b.在One方xml中配置

<set name="emps"  lazy="false" fetch="join"  cascade="all">
            <key column="deptNo"></key>
            <one-to-many class="com.wode.entity.Emp"/>
</set>

  c.级联添加

        Dept dept = new Dept();
        dept.setDeptNo(40);
        dept.setDname("销售部");
        dept.setLoc("红瓦寺");
        
        Emp emp = new Emp();
        emp.setEmpno(9527);
        emp.setEname("若湖");
        ...
        emp.setDept(dept);
        
        Emp emp2 = new Emp();
        emp2.setEmpno(9528);
        emp2.setEname("江瑕");
        ...
        emp2.setDept(dept);
        
        Set<Emp> emps = new HashSet<Emp>();
        emps.add(emp);
        emps.add(emp2);
        dept.setEmps(emps);
        
        session.save(dept);
        session.beginTransaction().commit();    

   d.级联删除

        Dept dept = (Dept) session.get(Dept.class, 40);
        session.delete(dept);
        session.beginTransaction().commit();

  e.通过Dept删除某个Emp

        Dept dept = (Dept) session.get(Dept.class, 40);
        Set<Emp> emps = dept.getEmps();
        Iterator<Emp> it = emps.iterator();
        while(it.hasNext()){
            if(it.next().getEname().equals("江瑕")){
                it.remove();
            }
        }
        session.beginTransaction().commit();

  f.查找所有的Dept以及所有Dept里面的Emp

        List<Dept> depts = session.createQuery("select distinct(d) from Dept d join fetch d.emps").list();
        for(Dept dept : depts){
            System.out.println(dept.getDname());
            for(Emp emp : dept.getEmps()){
                System.out.println(emp.getEname());
            }
        }

 

 

6.多对多

  a.配置xml

     <set name="courses" table="t_s_fk">
            <key column="sId"></key>
            <many-to-many class="Course" column="cId"></many-to-many>
        </set>

  b.添加(近增加相互之间的关系)

        Student stu = (Student) session.get(Student.class, 3);
        Course course1 = (Course) session.get(Course.class, 1);
        Course course2 = (Course) session.get(Course.class, 3);

        stu.getCourses().add(course1);
        stu.getCourses().add(course2);

        session.beginTransaction().commit();

  c.通过科目名称查找选了这门课程的学生

        Course course = (Course) session.get(Course.class, 1);
        Set<Student> stus = course.getStus();
        for(Student stu : stus){
            System.out.println(stu.getStuName());
        }

 

 

7.注解方式

  a.将 <mapping resource="com/wode/pojo/Emp.hbm.xml" /> 改为 <mapping class="com.wode.pojo.Emp" />

  b.标注方法参考Spring Data JPA

 

 

8.二级缓存

  a.在src下创建ehcache.xml

  b.在hibernate.cfg.xml中配置

        <property name="cache.use_second_level_cache">true</property>
        <property name="cache.use_query_cache">true</property>
        <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>

  c. 在Bean的映射配置xml中配置

 <cache usage="read-only" region="sampleCache1"/>

  d.若使用的是注解则加@注解

@Cache(usage = CacheConcurrencyStrategy.READ_ONLY)

 

 

9.Habernate在Spring中的使用

  a.在web.xml及applicationContext.xml中配置相应配置

  b.使用:

    @Autowired
    @Qualifier("sessionFactory")
    private SessionFactory sessionFactory;
    
    @Override
    public void addUser(User user) {
        // TODO Auto-generated method stub
        Session session = sessionFactory.getCurrentSession();
        session.save(user);
    }

 

转载于:https://www.cnblogs.com/vettel0329/p/6724468.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值