第一步:pom文件引入下面的依赖文件和querydsl的插件
第二步:
(1)创建一个实体类:
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "product_info")
public class ProductInfo implements Serializable{
/**
* 产品实体类
*/
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(generator = "idGenerator")
@GenericGenerator(name = "idGenerator",strategy = "uuid")
private String id;
@ApiModelProperty(value = "产品的名称")
@Column(name = "product_name")
private String productName;
@ApiModelProperty(value = "产品的颜色")
@Column(name = "product_color")
private String productColor;
@ApiModelProperty(value = "产品的编号")
@Column(name = "product_code")
private String productCode;
@ApiModelProperty(value = "产品的价格")
@Column(name = "product_price")
private String productPrice;
@ApiModelProperty(value = "产品的产地")
@Column(name = "product_palace")
private String productPalace;
@ApiModelProperty(value = "产品的净重")
@Column(name = "product_net_weight")
private Double productNetWeight;
@ApiModelProperty(value = "产品的生产日期")
@Column(name = "product_date")
private String productDate;
@ApiModelProperty(value = "产品保质期")
@Column(name = "expiration_date")
private Integer expirationDate;
}
(2)创建一个接口,分别继承JpaRepository
@Repository
public interface IProductRepository extends JpaRepository
(3)创建一个IProductService接口,里面包括 增加、删除、修改、查询分页方法
public interface IProductService {
void saveProduct(ProductInfo productInfo);
void deleteProduct(String[] ids);
ProductInfo updateProduct(String id);
Page
}
(4)创建一个ProductService implements IProductService,将 IProductRepository 的对象注入进去
@Service
public class ProductService implements IProductService {
@Autowired
private IProductRepository repository;
@Override
public void saveProduct(ProductInfo productInfo) {
repository.save(productInfo);
}
@Override
public void deleteProduct(String[] ids) {
for(String id : ids){
repository.delete(id);
}
}
@Override
public ProductInfo updateProduct(String id) {
return repository.findOne(id);
}
@Override
public Page
QProductInfo qp = QProductInfo.productInfo;
BooleanBuilder builder = new BooleanBuilder();
if(productName != null && !productName.equals("")){
builder.and(qp.productName.like("%"+productName+"%"));
}
if(productColor != null && !productColor.equals("")){
builder.and(qp.productColor.like("%"+productCode+"%"));
}
if(productCode != null && !productCode.equals("")){
builder.and(qp.productCode.like("%"+productCode+"%"));
}
return repository.findAll(builder,new PageRequest(page, limit));
}
}
第三步:
在application.properties中配置数据库:
spring.datasource.url = jdbc:mysql://localhost:3306/springdata?characterEncoding=utf8&useSSL=true
spring.datasource.username = root
spring.datasource.password = root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.generate-ddl = true
spring.jpa.hibernate.ddl-auto = update
spring.jpa.show-sql = true
spring.jpa.properties.hibernate.format_sql = true
注意点:光标紧跟每行最后一个字母就好,千万不要打空格。
第四步:测试
分别创建两个类:ProductTest、AppTestConfig
ProductTest类
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {AppTestConfig.class })
public class ProductionTest {
public static final Logger logger = LoggerFactory.getLogger(ProductTest.class);
@Autowired
private ProductService productService;
@Test
public void test_001_测试产品添加(){
ProductInfo productInfo = new ProductInfo();
productInfo.setProductName("pear");
productInfo.setProductColor("青色");
productInfo.setProductNetWeight(0.80);
productInfo.setProductCode("00011000");
productInfo.setExpirationDate(3);
productInfo.setProductPalace("陕西彬县");
productInfo.setProductDate("2017-09-30");
productService.saveProduct(productInfo);
logger.info("=============保存成功====================");
}
@Test
public void test_002_测试产品删除(){
String[] ids = new String[]{"4028c8605ef6c271015ef6c275660000"};
productService.deleteProduct(ids);
logger.info("=============删除成功====================");
}
@Test
public void test_003_修改产品信息(){
ProductInfo productInfo = productService.updateProduct("4028c8605ef66ae7015ef66aeb680000");
productInfo.setProductName("橘子");
productInfo.setProductCode("10110111");
productInfo.setProductPrice("5.25");
productService.saveProduct(productInfo);
logger.info("===============修改成功===============");
}
@Test
public void test_004_根据条件查询(){
Page
list = productService.searchByCondition("橘子", null, null, 0, 100);
TestCase.assertTrue(list.getContent().size()>0);
}
}
AppTestConfig类:
@Configuration
@ComponentScan(basePackages = { "" })//写自己的包结构 例如:com.spring.demo.*
@PropertySource("classpath:application.properties")
@EnableTransactionManagement
@EnableJpaRepositories(basePackages="")//repository包的全路径com.spring.demo.server.repository
public class AppTestConfig implements EnvironmentAware{
private Environment environment;
@Override
public void setEnvironment(Environment environment) {
this.environment=environment;
}
@Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(environment.getRequiredProperty("spring.datasource.driver-class-name"));
dataSource.setUrl(environment.getRequiredProperty("spring.datasource.url"));
dataSource.setUsername(environment.getRequiredProperty("spring.datasource.username"));
dataSource.setPassword(environment.getRequiredProperty("spring.datasource.password"));
return dataSource;
}
@Bean
@Autowired
public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource ds){
HibernateJpaVendorAdapter jpaVendorAdapter=new HibernateJpaVendorAdapter();
jpaVendorAdapter.setGenerateDdl(true);
jpaVendorAdapter.setShowSql(true);
Properties jpaProperties=new Properties();
jpaProperties.setProperty("hibernate.hbm2ddl.auto", "update");//validate,create,create-drop
LocalContainerEntityManagerFactoryBean emf=new LocalContainerEntityManagerFactoryBean();
emf.setDataSource(ds);
emf.setPackagesToScan("); //自己实体类的所在的包 com.spring.demo.domain
emf.setJpaVendorAdapter(jpaVendorAdapter);
emf.setJpaProperties(jpaProperties);
return emf;
}
@Bean
@Autowired
public PlatformTransactionManager transactionManager(LocalContainerEntityManagerFactoryBean emf){
JpaTransactionManager transactionManager=new JpaTransactionManager();
transactionManager.setEntityManagerFactory(emf.getObject());
return transactionManager;
}
@Bean
public PersistenceAnnotationBeanPostProcessor persistenceAnnotationBeanPostProcessor(){
PersistenceAnnotationBeanPostProcessor persistenceAnnotationBeanPostProcessor=new PersistenceAnnotationBeanPostProcessor();
return persistenceAnnotationBeanPostProcessor;
}
}