@Formula calculate temporary attribute.
Equivalent can be associated with the query field, then placed the entity as a property use.
Task: In the User physical layer, add an additional property to get the name field in the Test table.
1 table structure
User表
Test table
2 User physical layer (not part of the field.)
@Entity @Table(name = "user", catalog = "testdb") @DynamicUpdate public class User { private Integer id; private String uuid; private String test; @Id @GeneratedValue @Column(name = "id") public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } @Column(name = "uuid") public String getUuid() { return uuid; } public void setUuid(String uuid) { this.uuid = uuid; } @Formula("(select t.name from test as t where t.id=id)") public String getTest() { return test; } public void setTest(String test) { this.test = test; } }
We can see that in the getTest, an increase of @Formula comment. When the lookup table will be associated with the name Test table to the property.
note:
First, increase the alias table.
Second, pay attention to the two sql parentheses ()
Finally, the last t.id = id id, corresponding to @Colun (value = "id") on the property
3 Create a dao by jpa
@Repository public interface UserDao extends JpaRepository<User,Integer> { }
4 Test
@Autowired private UserDao userDao; @Test public void contextLoads() { System.out.println(userDao.findById(2).get().getTest()); }