spring与hibernate注解及XML方式集成

spring与hibernate注解及XML方式集成

Hibernate Xml方式

该种方式需要在sessionFactory中引入对应的hbm.xml文件,样例如下:

  <!-- spring-hibernate 整合 -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="hibernateProperties">
            <value>
                hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
                hibernate.jdbc.batch_size=25
                hibernate.jdbc.fetch_size=50
                hibernate.show_sql=true
            </value>
        </property>
        <property name="dataSource" ref="dataSource" />
        <property name="mappingLocations">
            <list>
                <value>classpath:/META-INF/gls.hibernate/User.hbm.xml</value>
                <value>classpath:/META-INF/gls.hibernate/Customer.hbm.xml</value>
                <value>classpath:/META-INF/gls.hibernate/BatchTransaction.hbm.xml</value>
                <value>classpath:/META-INF/gls.hibernate/PolicyTransaction.hbm.xml</value>
                <value>classpath:/META-INF/gls.hibernate/Policy.hbm.xml</value>
                <value>classpath:/META-INF/gls.hibernate/Email.hbm.xml</value>
                <value>classpath:/META-INF/gls.hibernate/BatchJobChunk.hbm.xml</value>
            </list>
        </property>
    </bean>

    <bean name="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <tx:annotation-driven transaction-manager="transactionManager" />

对于其他的DAO及其Service层,不做阐述了,不过对于DAO和Service建议建立BaseDao和BaseService使用泛型操作对应的model。

栗子来啦:

BaseDao

/**
 * baseDao class用于数据的CRUD操作
 * @author daniel.zhao
 *
 * @param <T>
 */
public interface BaseDao<T> {
    public void save(T entity);
    public void saveOrUpdate(T entity);
    public void update(T entity);
    public void delete(Serializable id);
    public T findById(Serializable id);
    public List<T> findByHql(String hql, Object...params);
    public List<T> findByHqlLimit(String hql, final Long start, final Long limit, Object...params);
}

DaoSupport

public class DaoSupport<T extends Serializable> implements BaseDao<T> {

    public static final Logger logger = LoggerFactory.getLogger(DaoSupport.class);
    
    private Class<T> clazz;
    
    @Autowired
    private SessionFactory sessionFactory;
    
    /**
     * 构造方法
     */
    public DaoSupport() {
        ParameterizedType type = (ParameterizedType) this.getClass().getGenericSuperclass();
        clazz = (Class<T>) type.getActualTypeArguments()[0];
        logger.info("BaseDao quety entity class: " + clazz.getName());
    }
    
    public Session getSession() {
        return sessionFactory.getCurrentSession();
    }

    @Override
    public void save(T entity) {
        this.getSession().save(entity);
    }

    @Override
    public void saveOrUpdate(T entity) {
        this.getSession().saveOrUpdate(entity);
    }

    @Override
    public void update(T entity) {
        this.getSession().update(entity);
    }

    @Override
    public void delete(Serializable id) {
        this.getSession().delete(this.findById(id));
    }

    @Override
    public T findById(Serializable id) {
        return (T) this.getSession().get(this.clazz, id);
    }

    @Override
    public List<T> findByHql(String hql, Object... params) {
        Query query = this.getSession().createQuery(hql);
        for (int i = 0; params != null && i < params.length; i++) {
            query.setParameter(i, params[i]);
        }
        return query.list();
    }

    @Override
    public List<T> findByHqlLimit(String hql, Long start, Long limit, Object... params) {
        Query query = this.getSession().createQuery(hql);
        for (int i = 0; params != null && i < params.length; i++) {
            query.setParameter(i, params[i]);
        }
        query.setFirstResult(start.intValue());
        query.setMaxResults(limit.intValue());
        return query.list();
    }
}

BaseService

public interface BaseService<T> {
    public void save(T entity);
    public void saveOrUpdate(T entity);
    public void update(T entity);
    public void delete(Serializable id);
    public T findById(Serializable id);
    public List<T> findByHql(String hql, Object...params);
    public List<T> findByHqlLimit(String hql, final Long start, final Long limit, Object...params);
}

BaseServiceImpl

@Transactional
public class BaseServiceImpl<T> implements BaseService<T> {

    private BaseDao<T> dao;
    
    @Resource
    public void setDao(BaseDao<T> dao) {
        this.dao = dao;
    }
    
    @Override
    public void save(T entity) {
        dao.save(entity);
    }

    @Override
    public void saveOrUpdate(T entity) {
        dao.saveOrUpdate(entity);
    }

    @Override
    public void update(T entity) {
        dao.update(entity);
    }

    @Override
    public void delete(Serializable id) {
        dao.delete(id);
    }

    @Override
    public T findById(Serializable id) {
        return dao.findById(id);
    }

    @Override
    public List<T> findByHql(String hql, Object... params) {
        return dao.findByHql(hql, params);
    }

    @Override
    public List<T> findByHqlLimit(String hql, Long start, Long limit, Object... params) {
        return dao.findByHqlLimit(hql, start, limit, params);
    }

}

 注解方式

 Hibernate Entity

@Entity
@Table(name = "t_user")
public class User implements Serializable {
    /**
     * 
     */
    private static final long serialVersionUID = -9042615274714038279L;

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

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

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

    @Column(name = "age")
    private Integer age;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name == null ? null : name.trim();
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password == null ? null : password.trim();
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
    
    @Override
    public String toString() {
        return "User[id=" + id + ", name=" + name + ",age=" + age + "]";
    }
}

Hibernate Xml

  <!-- spring-hibernate 整合 -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="hibernateProperties">
            <value>
                hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
                hibernate.jdbc.batch_size=25
                hibernate.jdbc.fetch_size=50
                hibernate.show_sql=true
            </value>
        </property>
        <property name="dataSource" ref="dataSource" />
        <property name="annotatedClasses">
            <list>
                <value>com.ebao.life.model.User</value>
            </list>
        </property>
    </bean>

    <bean name="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <tx:annotation-driven transaction-manager="transactionManager" />

Junit Test

@RunWith(JUnit4ClassRunner.class)
@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = false)
@ContextConfiguration(classes = { PropertyConfig.class, DataSourceConfig.class, HibernateAnnotationConfig.class })
public class HibernateAnnotationTest {

    public static final Logger logger = LoggerFactory.getLogger(HibernateAnnotationTest.class);
    
    @Resource(name = UserService.BEAN_DEFAULT)
    private UserService userService;
    
    @Test
    public void testInsert() {
        User user = new User();
        user.setName("daniel-zhao-001");
        user.setPassword("password");
        user.setAge(28);
        userService.save(user);
    }
}

 

posted @ 2017-03-17 17:52  低调的小黑  阅读(3222)  评论(0编辑  收藏  举报