SpringBoot+SpringDataJpa后台常用注解

来源:互联网 发布:怎样在淘宝买东西 编辑:程序博客网 时间:2024/06/07 10:34



SpringDataJpa中sqlite的时间格式必须为'2017-03-23 09:10:29.100'  否则报错


com.controller
@RestController  表示该类是controller层 //@RestController注解相当于@ResponseBody + @Controller合在一起的作用。
@RequestMapping("/")  请求路径
@Autowired spring自动创建该对象的bean,生成对象
@ResponseBody  返回结果放入body数据区,返回的不是html页面,一般为json


com.service
@Service  表示该类是service层


com.repository
@Query("select t from UsersEntity t where t.userName=?1 and t.from = ?2") 
UsersEntity findByUserNameAndFrom(String userName,String from);
//执行findByUserNameAndFrom的方法的时候不会去调用SpringDataJpa的匹配规则,直接调用query后面的hql语句


@Query("select * from tb_task t where t.task_name = ?1", nativeQuery = true)
  Task findByTaskName(String taskName);
  //执行findByTaskName的方法的时候不会去调用SpringDataJpa的匹配规则,直接调用query后面的sql语句


com.entity
@Entity  表示该类是entity
@Table(name = "users") //表名
@Id  表示该属性对应的字段是主键
@GeneratedValue(strategy = GenerationType.AUTO) //主键生成策略
@Column(name = "u_id") //对应的字段名




@RequestMapping("/findByUserNameAndFrom/{userName}/{from}")
@ResponseBody
public String findByUserNameAndFrom(@PathVariable String userName, @PathVariable String from) {
return userService.findByUserNameAndFrom(userName, from);
}
//@PathVariable 使用RequestMapping路径中的参数

下面是SpringDataJpa方法名命名规则:

关键字方法命名sql where字句AndfindByNameAndPwdwhere name= ? and pwd =?OrfindByNameOrSexwhere name= ? or sex=?Is,EqualsfindById,findByIdEqualswhere id= ?BetweenfindByIdBetweenwhere id between ? and ?LessThanfindByIdLessThanwhere id < ?LessThanEqualsfindByIdLessThanEqualswhere id <= ?GreaterThanfindByIdGreaterThanwhere id > ?GreaterThanEqualsfindByIdGreaterThanEqualswhere id > = ?AfterfindByIdAfterwhere id > ?BeforefindByIdBeforewhere id < ?IsNullfindByNameIsNullwhere name is nullisNotNull,NotNullfindByNameNotNullwhere name is not nullLikefindByNameLikewhere name like ?NotLikefindByNameNotLikewhere name not like ?

StartingWith

findByNameStartingWithwhere name like '?%'EndingWithfindByNameEndingWithwhere name like '%?'ContainingfindByNameContainingwhere name like '%?%'OrderByfindByIdOrderByXDescwhere id=? order by x descNotfindByNameNotwhere name <> ?InfindByIdIn(Collection<?> c)where id in (?)NotInfindByIdNotIn(Collection<?> c)where id not  in (?)True

findByAaaTue

where aaa = trueFalsefindByAaaFalsewhere aaa = falseIgnoreCasefindByNameIgnoreCasewhere UPPER(name)=UPPER(?)


springboot测试:
@RunWith(SpringJUnit4ClassRunner.class)
// 指定我们SpringBoot工程的Application启动类
@SpringBootTest(classes = { Application.class })
// @SpringApplicationConfiguration(classes = Application.class)
// 由于是Web项目,Junit需要模拟ServletContext,因此我们需要给我们的测试类加上@WebAppConfiguration。
@WebAppConfiguration







0 0
原创粉丝点击