博主之前用的C#ORM 比较多,就想着Hibernate是否也会支持自定义查询函数并映射到实体类(无法创建视图的时候使用)。解决方案如下:
定义类以及sql:
@Entity
@Immutable
@Subselect(value = "select t.id,t.name,m.money from test t left outer join moneys m on t.id=m.id")
//@Synchronize({ "Note", "Money" })
public class ImmuTable {
@Id
protected Long id;
protected String name;
protected String money;
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getMoney() {
return this.money;
}
public void setMoney(String money) {
this.money = money;
}
}
其中select语句就是根据数据库来的,test 以及moneys就是表名。
定义repository
@Repository
public interface immu extends JpaRepository<ImmuTable, Long> {
}
定义rest接口
@RestController
@RequestMapping("/immu")
public class testimmu {
@Autowired
immu testi;
@RequestMapping("/all")
public List<ImmuTable> get()
{
return testi.findAll();
}
@RequestMapping(value="/one/{id}",method=RequestMethod.GET)
public ImmuTable getOne(@PathVariable("id") Long id)
{
Optional<ImmuTable> tt= testi.findById(id);
return tt.get();
}
@RequestMapping("/update/{id}/{name}/{money}")
public List<ImmuTable> Insert(@PathVariable("id") Long id,@PathVariable("name") String name,@PathVariable("money") String money)
{
Optional<ImmuTable> tt= testi.findById(id);
ImmuTable test= tt.get();
test.setMoney(money);
test.setName(name);
return testi.findAll();
}
}