# 1. 实体类
1. 动态更新数据,只更新有值的数据
>@DynamicUpdate
2. 将实体类映射为表,如果名字不匹配使用name=tablename
>@Entity
3. 将属性映射为主键,并设置自增
> @Id @GenericValue
4. 自动生成常用方法
> @Data @Getter @Setter
> 安装lombok教程
5. 该属性不会映射到库里
>@Transient
6. 不希望返回JSON的属性
>@JsonIgnore
7. 只返回非空的JSON
>@JsonInclude
8. 将JSON转换为List
>gson.fromJSON(json,new TypeToken<List<T>>(){}.getType());
9. 将日期转换为Long做法:新建一个类如下,再将实体类日期属性上加
>@JsonSerialize(using=Date2LongSerializer.class)
public class Date2LongSerializer extends JsonSerializer<Date> {
@Override
public void serialize(Date date, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
jsonGenerator.writeNumber(date.getTime() / 1000);
}
}
10. 添加额外配置文件
> @ImportResource({"classpath:xxx-context.xml","classpath:yyy-context.xml"})
11. 添加额外属性文件
> @PropertyResource({"classpath:xxx.properties","classpath:yyy.properties"})
12. 读取属性文件,配置类型安全的bean
> @Component
@ConfigurationProperties(prefix="book",location={"classpath:config/book.properties"})
---
# 2. 持久层
[点击查看JPA语法](https://www.cnblogs.com/wangdaijun/p/5523923.html)
//创建持久层接口
//继承JpaRepository<对象,主键>自带基本的增删改查功能
//如果有特殊查询,请按照给定的语法,写出方法即可
//语法规则
public interface ProductInfoRepository extends JpaRepository<ProductInfo, String> {
List<Object> findByObjIdIn(List<Integer> idList);
}
* 更多内容参考第9章
---
# 2. 业务层
1. 接口+实现类的方式
> public interface DemoService {
//根据id获得对象
Object findOne(Integer id);
//获得所有对象,JPA会根据实体的相关注解进行查询
List<Object> findAll();
//根据给定的id集合,查找符合条件的对象集合
List<Object> findByObjIdIn(List<Integer> idList);
}
@Service
public class DemoServiceImpl implements DemoService {
//注入DAO层
@Autowired
private CtsDAO dao;
//实现方法的业务逻辑
@Override
public Object findById(Integer id) {
return dao.findById(id);
}
}
---
# 3. 控制层
1. 类级注解
>@RestController(返回Json格式专用) @RequestMapping("/\*/*")
2. 方法级注解
>@GetMapping("/list")@PostMapping("/list")
@PutMapping() @DeleteMapping()
3. 参数级注解
>@RequestParam(value="id",defaultValue="1")String id
required=false,参数可为空
//get请求示例
@GetMapping("/list")
//指定参数和默认值
public ModelAndView list(@RequestParam(value="id",defaultValue="1")String id, Map<String, Object> map) {
List<ProductCategory> categoryList = categoryService.findAll();
//将数据放到map里
map.put("categoryList", categoryList);
//返回视图和map,供解析
return new ModelAndView("category/list", map);
}
//post请求示例
//使用表单验证类接收表单
@PostMapping("/save")
public ModelAndView save(@Valid CategoryForm form, BindingResult bindingResult, Map<String, Object> map) {
//...处理逻辑
//保存对象
service.save(productCategory);
//返回视图名和需要绑定的数据
return new ModelAndView("common/success", map);
}
//分页请求示例
/**
* 列表
* @param page 第几页, 从1页开始
* @param size 一页有多少条数据