美文网首页
spring with straight Hibernate

spring with straight Hibernate

作者: cdz620 | 来源:发表于2020-03-05 10:21 被阅读0次

warning

glossary

org.hibernate.Session

主要核心的工作接口:org.hibernate.Session,所有的开发围绕这个展开

SessionFactory

职责: 打开,关闭,管理Hibernate Sessions

使用姿势

  1. 声明一个SessionFactory,通过SessionFactory 获取一个session
  2. ORM映射
  3. 增删改查

配饰SessionFactory

spring 提供了三个SessionFactory,三种核心差别是如何配置orm映射关系:

  • org.springframework.orm.hibernate3.LocalSessionFactoryBean: 适用于Hibernate 3.2, 使用xml配置映射关系
  • org.springframework.orm.hibernate3.annotation.AnnotationSession-
    FactoryBean
  • org.springframework.orm.hibernate4.LocalSessionFactoryBean

配置SessionFactory三步骤

  1. 配置DataSource Bean:连接信息
  2. 加载映射的orm:xml或者自动扫描
  3. 设置Property:声明使用什么数据库

org.springframework.orm.hibernate3.LocalSessionFactoryBean

适用场景:Hibernate 3.2 与4.0之间,习惯用xml配置映射关系

@Bean
public LocalSessionFactoryBean sessionFactory(DataSource dataSource) {
    LocalSessionFactoryBean sfb = new LocalSessionFactoryBean();
    sfb.setDataSource(dataSource); //1
    sfb.setMappingResources(new String[]{"Spitter.hbm.xml"});//2用xml配置映射关系
    Properties props = new Properties();
    props.setProperty("dialect", "org.hibernate.dialect.H2Dialect"); //3
    sfb.setHibernateProperties(props);
    return sfb;
}

org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean

适用场景:Hibernate 3.2 与4.0之间,习惯用注释配置关系

@Bean
public AnnotationSessionFactoryBean sessionFactory(DataSource ds) {
  AnnotationSessionFactoryBean sfb = new AnnotationSessionFactoryBean();
  sfb.setDataSource(ds);
  sfb.setPackagesToScan(new String[] { "com.habuma.spittr.domain" });
  Properties props = new Properties();
  props.setProperty("dialect", "org.hibernate.dialect.H2Dialect");
  sfb.setHibernateProperties(props);
  return sfb;
}

org.springframework.orm.hibernate4.LocalSessionFactoryBean

  • 适用于Hibernate 4.0+,可以使用xml或者annotation进行配置映射关系
@Bean
public LocalSessionFactoryBean sessionFactory(DataSource dataSource) {
  LocalSessionFactoryBean sfb = new LocalSessionFactoryBean();
  sfb.setDataSource(dataSource);
  sfb.setPackagesToScan(new String[] { "com.habuma.spittr.domain" });
  Properties props = new Properties();
  props.setProperty("dialect", "org.hibernate.dialect.H2Dialect");
  sfb.setHibernateProperties(props);
  return sfb;
}
  • 另一种配置映射关系方式:
sfb.setAnnotatedClasses(
          new Class<?>[] { Spitter.class, Spittle.class }
);

使用demo

package spittr.db.hibernate4;

import java.io.Serializable;
import java.util.List;

import javax.inject.Inject;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import spittr.db.SpitterRepository;
import spittr.domain.Spitter;

@Repository
public class HibernateSpitterRepository implements SpitterRepository {

    private SessionFactory sessionFactory;

    @Inject
    public HibernateSpitterRepository(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;         //<co id="co_InjectSessionFactory"/>
    }

    private Session currentSession() {
        return sessionFactory.getCurrentSession();//<co id="co_RetrieveCurrentSession"/>
    }

    public long count() {
        return findAll().size();
    }

    public Spitter save(Spitter spitter) {
        Serializable id = currentSession().save(spitter);  //<co id="co_UseCurrentSession"/>
        return new Spitter((Long) id,
                spitter.getUsername(),
                spitter.getPassword(),
                spitter.getFullName(),
                spitter.getEmail(),
                spitter.isUpdateByEmail());
    }

    public Spitter findOne(long id) {
        return (Spitter) currentSession().get(Spitter.class, id);
    }

    public Spitter findByUsername(String username) {
        return (Spitter) currentSession()
                .createCriteria(Spitter.class)
                .add(Restrictions.eq("username", username))
                .list().get(0);
    }

    public List<Spitter> findAll() {
        return (List<Spitter>) currentSession()
                .createCriteria(Spitter.class).list();
    }

}

配置ORM

package spittr.domain;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;


@Entity
public class Spitter {
    
    private Spitter() {}

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long id;

    @Column(name="username")
    private String username;

    @Column(name="password")
    private String password;

    @Column(name="fullname")
    private String fullName;

    @Column(name="email")
    private String email;

    @Column(name="updateByEmail")
    private boolean updateByEmail;

    public Spitter(Long id, String username, String password, String fullName, String email, boolean updateByEmail) {
        this.id = id;
        this.username = username;
        this.password = password;
        this.fullName = fullName;
        this.email = email;
        this.updateByEmail = updateByEmail;
    }

    public Long getId() {
        return id;
    }

    public String getUsername() {
        return username;
    }

    public String getPassword() {
        return password;
    }

    public String getFullName() {
        return fullName;
    }

    public String getEmail() {
        return email;
    }

    public boolean isUpdateByEmail() {
        return updateByEmail;
    }

}

增删改查

package spittr.db.jpa;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.stereotype.Repository;

import spittr.db.SpittleRepository;
import spittr.domain.Spittle;

@Repository
public class JpaSpittleRepository implements SpittleRepository {

  @PersistenceContext
  private EntityManager entityManager;

  public long count() {
    return findAll().size();
  }

  public List<Spittle> findRecent() {
    return findRecent(10);
  }

  public List<Spittle> findRecent(int count) {
    return (List<Spittle>) entityManager.createQuery("select s from Spittle s order by s.postedTime desc")
        .setMaxResults(count)
        .getResultList();
  }

  public Spittle findOne(long id) {
    return entityManager.find(Spittle.class, id);
  }

  public Spittle save(Spittle spittle) {
    entityManager.persist(spittle);
    return spittle;
  }

  public List<Spittle> findBySpitterId(long spitterId) {
    return (List<Spittle>) entityManager.createQuery("select s from Spittle s, Spitter sp where s.spitter = sp and sp.id=? order by s.postedTime desc")
        .setParameter(1, spitterId)
        .getResultList();
  }

  public void delete(long id) {
    entityManager.remove(findOne(id));
  }

  public List<Spittle> findAll() {
    return (List<Spittle>) entityManager.createQuery("select s from Spittle s").getResultList();
  }

}

相关文章

网友评论

      本文标题:spring with straight Hibernate

      本文链接:https://www.haomeiwen.com/subject/btdjchtx.html