优缺点
优点
- 无须依赖mybatis等框架,无xml。
- 适用于表相互关联性不大的场景,使用jpa会使项目更精简。
- java创建号实体及实体的表信息,运行项目,数据库中就会生成对应的表,使用jpa的项目有利于项目移植。
- dao接口继承Jpa的Repository后,就可以直接调用其已有方法进行数据表进行操作,如数据的增删改,分页,排序。
- 可直接根据id进行条件查询,指定列的条件查询只需要在dao中按jpa的语法(方法名驼峰命名),写个相关的抽象方法就可以使用查询功能了。
- 需要写hql的,可在dao中所需抽象方法上,使用对应注解(如@Query…),注解的括号里书写相关hql。
缺点
- 分页时,起始值或起始值加分页大小超过总大小的话,会查不到数据。
- 复杂的查询场景使用起来比较费劲,比如条件搜索+分页+排序,需要Example、Sort、PageRequest类都使用方可。
- 注解式的hql中表名、列名不能是参数,不利于表查询的灵活使用。
- 注解式的hql中无分页语法。
- jpa在注解中使用原生sql时,会把所在方法的形参类型格式化,比如字符串会加上单引号。
- 分页不能与jpa Repository接口结合复用,比较费劲。
要点代码示例
**提示:**按如下步骤操作后,运行springboot主类,会直接在mysql数据库中生成对应的表,可以手动在表中造几条数据,测试jpa使用效果
pom相关依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
application.properties配置相关
# 应用名称
#spring.application.name=data_show
#服务环境路径
server.servlet.context-path=/data_show
# 应用服务 WEB 访问端口
server.port=8080
# 数据库驱动:
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# 数据源名称
spring.datasource.name=defaultDataSource
# 数据库连接地址
spring.datasource.url=jdbc:mysql://betterhost:3305/hanxs?serverTimezone=UTC
# 数据库用户名&密码:
spring.datasource.username=***
spring.datasource.password=***
spring.jpa.hibernate.ddl-auto=none
spring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialect
#
spring.jpa.generate-ddl=true
#语句打印
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.properties.hibernate.type=trace
spring.jpa.properties.hibernate.use_sql_comments=true
spring.jpa.properties.hibernate.jdbc.batch_size=50
#logging.level.org.hibernate.type.descriptor.sql=trace
logging.level.org.springframework=error
logging.pattern.console=%d{yyyy/MM/dd-HH:mm:ss} %level [%thread] %caller{1} - %msg%n
创建DO实体
package com.example.data_show.entity;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* @description:呼叫信令基础标签表(Call_Information_Label)
* @author: hanxs - 28Rules
* @date: 2021/03/02
*/
@Getter
@Setter
@ToString
@Entity
@Table(name = "call_information_label")
public class CallInformationEntity {
@Id
@GeneratedValue(strategy= GenerationType.IDENTITY)//strategy=GenerationType.IDENTITY 自增长
@Column(name="id")
private int id;//1 id int 主键ID
@Column(name="call_numeber")
private String callNumber;//2 Call_Numeber String 主叫号码
}
创建BaseDao
package com.example.data_show.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.NoRepositoryBean;
import java.util.List;
/**
* @description:
* @author: hanxs - 28Rules
* @date: 2021/03/02
*/
@NoRepositoryBean
public interface BaseDao<T, ID> extends JpaRepository<T, ID>, JpaSpecificationExecutor {
List<T> queryListById(int id);
List<T> queryListByCallNumber(String calNumber, String sortColName);
List<T> queryListByCallNumber1(String colNumber, String sortColName, int currentPageNum, int pageSize);
}
创建Dao
package com.example.data_show.dao;
import com.example.data_show.entity.CallInformationEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import java.util.List;
/**
* @description:
* @author: hanxs - 28Rules
* @date: 2021/03/02
*/
public interface CallInformationDao extends BaseDao<CallInformationEntity,Integer>{
@Query(value = " from CallInformationEntity where id = ?1")
List<CallInformationEntity> query(int id);
@Query(value = "select * from call_information_label where id = ?1",nativeQuery = true)
@Override
List<CallInformationEntity> queryListById(int id);
@Query(value = " from CallInformationEntity where callNumber = ?1 order by ?2 ")
@Override
List<CallInformationEntity> queryListByCallNumber(String calNumber, String sortColName);
@Query(value = "select * from call_information_label where call_numeber = ?1 order by ?2 limit ?3 ,?4",nativeQuery = true)
List<CallInformationEntity> queryListByCallNumber1(String colNumber,String sortColName, int currentPageNum, int pageSize);
}
测试
package com.example.data_show;
import com.example.data_show.common.CommonPageDTO;
import com.example.data_show.dao.CallInformationDao;
import com.example.data_show.entity.CallInformationEntity;
import com.example.data_show.service.CallInformationService;
import lombok.extern.log4j.Log4j2;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
/**
* @description:
* @author: hanxs - 28Rules
* @date: 2021/03/02
*/
//@RunWith(SpringJUnit4ClassRunner.class)
//@ContextConfiguration("classpath:applicationContext.xml")
//@ContextConfiguration("classpath:application.properties")
@RunWith(SpringRunner.class)
@SpringBootTest
@Configuration
@Log4j2
@ComponentScan({/*"cn.com.cintel.eipp_common.**",*/"com.example.data_show.**"})
public class DataShowTest {
@Autowired
CallInformationDao callInformationDao;
@Autowired
CallInformationService callInformationService;
@Test
public void selectDao(){
log.info(callInformationDao.query(0));
List<CallInformationEntity> entityList = callInformationDao.queryListById(0);
log.info(entityList.size());
// List<CallInformationEntity> entityList1 = callInformationDao.queryListByCallNumber1("call_information_label",
// "callNumber", "1", 1, 2, "id");
//
List<CallInformationEntity> entityList1 = callInformationDao.queryListByCallNumber1("10", "id", 0, 3);
log.info(entityList1.size());
}
}