jpa and spring data jpa development

jpa and spring data jpa development

//jpa generates code

Direct use of single-table query requires a standardized interface

@Repository

@Transactional

public interface BasSpsxValueDao extends JpaRepository<BasSpsxValueBean, Long>,IBasSpsxValueDao {}The implementation class of this interface is automatically generated

The key to determining whether you can use jpa's native built-in sql operation is JpaRepository<BasSpsxValueBean, Long (primary key type)>

When there are multiple tables, you can create another native interface. At this time, you need to write the implementation class yourself. In order to clearly express the relationship between the custom native interface and the single-table interface in the framework structure, let the interface inherit

But when the interface is injected, BasSpsxValueDao should be injected instead of IBasSpsxValueDao

<jpa:repositories base-package="com.esteel.web.dao"></jpa:repositories>//Scan Dao's Lujin and its sub-packages, automatically generate impl, and add it to this directory

public interface IBasSpsxValueDao {

 

/**

* Query the unique typical value based on valueKey and parentValue

* @param valueKey

* @param parentValue

* @return

*/

public String getDefaultValue(String valueKey,String parentValue);

 

/**

* Query the valueKey of all typical values 

* Used to query whether there is a typical value

* @return

*/

public List<String> getAllDxzValueKey();

 

public List<BasSpsxValueBeanVo> spsxPartKeycdpzzzMap();

public List<BasSpsxValueBeanVo> spsxKeycdpzzzMap();

public List<BasSpsxValueBeanVo> rltnPartKeypmcjzzMap();

}

 

public class BasSpsxValueDaoImpl implements IBasSpsxValueDao {

 

@PersistenceContext

private EntityManager em;

 

@Autowired

public ESteelSqlSessionTemplate sqlSessionTemplate;

 

/**

* 查询默认值

*/

@Override

@Cacheable("BasSpsxValueDaoImpl.getDefaultValue")

public String getDefaultValue(String valueKey, String parentValue) {

 

Query query;

if (StringUtils.isEmpty(parentValue)) {

String sql = "select valuetype||defaultValue from tb_bas_dxz where valueKey=:valueKey and parentValue is null";

query = em.createNativeQuery(sql);

query.setParameter("valueKey", valueKey);

} else {

String sql = "select valuetype||defaultValue from tb_bas_dxz where valueKey=:valueKey and parentValue=:parentValue";

query = em.createNativeQuery(sql);

query.setParameter("valueKey", valueKey);

query.setParameter("parentValue", parentValue);

}

@SuppressWarnings("unchecked")

List<String> list = query.getResultList();

 

if (list.isEmpty()) {

return "";

} else {

return list.get(0);

}

 

}

 

@Override

@Cacheable("BasSpsxValueDaoImpl")

public List<String> getAllDxzValueKey() {

String sql = "select valuekey from tb_bas_dxz";

Query query = em.createNativeQuery(sql);

 

@SuppressWarnings("unchecked")

List<String> list = query.getResultList();

return list;

}

 

@Override

public List<BasSpsxValueBeanVo> spsxPartKeycdpzzzMap() {

return sqlSessionTemplate.selectList("basSpsxValue.spsxPartKeycdpzzzMap");

}

 

@Override

public List<BasSpsxValueBeanVo> spsxKeycdpzzzMap() {

return sqlSessionTemplate.selectList("basSpsxValue.spsxKeycdpzzzMap");

}

 

@Override

public List<BasSpsxValueBeanVo> rltnPartKeypmcjzzMap() {

return sqlSessionTemplate.selectList("basSpsxValue.rltnPartKeypmcjzzMap");

}

 

}

 

 

///hibernate

以下都是基于jpa的

 

@PersistenceContext

private EntityManager em;注入下面这个工厂类,然后使用操作数据库(dao中用)

 

<bean id="entityManagerFactory"//hibernate

class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">

<property name="dataSource" ref="dataSource"></property>

<property name="jpaVendorAdapter" ref="jpaVendorAdapter"></property>

<property name="persistenceUnitName" value="esteel"></property>

<property name="packagesToScan" value="com.esteel.web.entity"></property>//扫描实体的路径,不包括他的子包,新增的时候要符合这个目录

</bean>

 

 

<!-- Jpa 事务管理器  -->自动就是注解

  <bean id="transactionManager"  class="org.springframework.orm.jpa.JpaTransactionManager">

    <property name="entityManagerFactory" ref="entityManagerFactory" />

  </bean>

 

 

 

目前我用的是

 <!-- 设定transactionManager -->

    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

        <property name="dataSource" ref="dataSource" />

    </bean>

 

    <!-- 使用annotation定义事务 -->

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

 

@Repository  //如果是jdk代理放到impl,dao层都可以

@Transactional

public interface BasAffixDao extends JpaRepository<BasAffixBean, Long>

 

 

@Repository

@Transactional

public class AffixDaoImpl implements AffixDao {

 

    @Autowired

    public ESteelSqlSessionTemplate sqlSessionTemplate;

 

    public interface ITbCusUserDao {

    public List<TbCusUserBean> warePartKeyzzMap();这种自定义的接口,如果不是用的@Query,那么需要这个bean对应的mapper.xml中有相应的sql

}

 

<select id="warePartKeyzzMap" resultMap="basBedMap">

SELECT T.WARE_KEY,T.WAREKIND_KEY,T.WARE_ID,T.WARE_NAME,T.SPEC_FORMULA,

T.DATA_MEM_TABLE,T.PICTURE_ADDRESS,T.IS_SHOW,T.ORDER_NUM,T.EN,T.ENSHORT,T.BZ,'N' SELECTED

FROM TB_BAS_BED T WHERE T.IS_SHOW='Y' order by WAREKIND_KEY,WARE_KEY, ORDER_NUM

</select>

 

@Repository

@Transactional

public interface TbCusUserDao extends JpaRepository<TbCusUserBean, Long>,ITbCusUserDao{

 

public void deleteByObjKey(Integer objKey);//接口中的方法By后面的字段需要bean有,否则出错(继承了这个的接口的情况下extends JpaRepository)

}

 

///mybatis(这个框架中只有hibernate是用了事务的)

1,这个框架的mapper.xml不是扫描的是配置的方式

 

2,<bean id="sqlSessionTemplate" class="com.esteel.web.utils.ESteelSqlSessionTemplate" c:sqlSessionFactory-ref="sqlSessionFactory"></bean>//mybatis

  public class ESteelSqlSessionTemplate extends SqlSessionTemplate

 

public ESteelSqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {

super(sqlSessionFactory);

}

直接用这个模板也可调用mybatis的内置方法(在不继承mapper通用接口下,通过扫描生成实现类的情况下),只不过是手动写实现类(dao中用)

 

 

是实现类的要么是mybatis,要么是需要多表查询的hibernate

 

 

 

修改Eclipse项目使之支持JPA工具 

http://blog.sina.com.cn/s/blog_484d87770100u4nm.html

用Eclipse建立了一个Web项目,想通过eclipse的JPA Tools为项目生成数据库实体Bean,但右键菜单里看不到JPA Tools选项。

于是招到一个类似的项目(能够右键看到JPA Tools),查看其工程路径下.setting/org.eclipse.wst.common.project.facet.core.xml文件,

发现<faceted-prject>标签内有这样一句“<installed facet="jpt.jpa" version="1.0"/>”于是copy这句到了新建项目的对应文件中。刷新一下项目,

再右键后,于是就看到了希望见到的JPA Tools。

http://my.oschina.net/hcliu/blog/401262//使用 jpa tool

 

 

无论自己定义还是jpa代理的dao,注入方式掉用

@Autowired

private BasAffixDao basAffixDao; 

 

 

 

//接下来就是jpa注解了,可以用

 

TbCusUserBean

 

 

jpa规范:

http://www.ibm.com/developerworks/cn/opensource/os-cn-spring-jpa/   spring data jpa(dao层上的注解,@query,方法名解析成sql)org.springframework.data.jpa

http://java-zone.org/1287.html   jpa(实体上的注解)javax.persistence

And --- 等价于 SQL 中的 and 关键字,比如 findByUsernameAndPassword(String user, Striang pwd);

Or --- 等价于 SQL 中的 or 关键字,比如 findByUsernameOrAddress(String user, String addr);

Between --- 等价于 SQL 中的 between 关键字,比如 findBySalaryBetween(int max, int min);

LessThan --- 等价于 SQL 中的 "<",比如 findBySalaryLessThan(int max);

GreaterThan --- 等价于 SQL 中的">",比如 findBySalaryGreaterThan(int min);

IsNull --- 等价于 SQL 中的 "is null",比如 findByUsernameIsNull();

IsNotNull --- 等价于 SQL 中的 "is not null",比如 findByUsernameIsNotNull();

NotNull --- 与 IsNotNull 等价;

Like --- 等价于 SQL 中的 "like",比如 findByUsernameLike(String user);

NotLike --- 等价于 SQL 中的 "not like",比如 findByUsernameNotLike(String user);

OrderBy --- 等价于 SQL 中的 "order by",比如 findByUsernameOrderBySalaryAsc(String user);

Not --- 等价于 SQL 中的 "! =",比如 findByUsernameNot(String user);

In --- 等价于 SQL 中的 "in",比如 findByUsernameIn(Collection<String> userList) ,方法的参数可以是 Collection 类型,也可以是数组或者不定长参数;

NotIn --- 等价于 SQL 中的 "not in",比如 findByUsernameNotIn(Collection<String> userList) ,方法的参数可以是 Collection 类型,也可以是数组或者不定长参数;

 

public BasAffixBean findFirstByTableNameAndTableKey(String tableName,String tableKey);//表的主键

 

        //这种按照规范自动生成sql(只是单表)

public void deleteByTableNameAndTableKey(String tableName,String tableKey);

public void deleteByTableKeyAndAffixType(String tableKey,String affixType);

public List<BasAffixBean>  findByTableNameAndTableKeyOrderByAffixKey(String tableName,String tableKey);

@Cacheable("findByAreaLevel")

public List<BasAreaBean> findByAreaLevel(String areaLevel);

@Cacheable("BasBedDao.findByWarekindKey")

public List<BasBedBean> findByWarekindKeyOrderByWareKey(long warekindKey);

        //一些直接的save等不带具体字段的不用写,service中直接调用

 

        //这种类似xml中sql,合适复杂sql

@Cacheable("BasBedSrtBean")

@Query("SELECT b FROM BasBedSrtBean b")

public List<BasBedSrtBean> findAllSrt();

 

@Cacheable("BasBedSrtBean")

@Query("SELECT b FROM BasBedSrtBean b WHERE b.bz LIKE %:bz%")//适合多表查询

public List<BasBedSrtBean> findByBz(@Param("bz")String bz);

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326509351&siteId=291194637