我使用JDBI创建了一个简单的REST应用程序和dropwizard。下一步是整合一个与另一个具有一对多关系的新资源。直到现在我都无法弄清楚如何在我的DAO中创建一个方法来检索一个包含另一个表中对象列表的对象。如何使用JDBI SQL对象API创建一对多关系?
的POJO的描述是这样的:
public class User {
private int id;
private String name;
public User(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class Account {
private int id;
private String name;
private List<User> users;
public Account(int id, String name, List<User> users) {
this.id = id;
this.name = name;
this.users = users;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<User> getUsers() {
return name;
}
public void setUsers(List<Users> users) {
this.users = users;
}
}
的DAO应该是这个样子
public interface AccountDAO {
@Mapper(AccountMapper.class)
@SqlQuery("SELECT Account.id, Account.name, User.name as u_name FROM Account LEFT JOIN User ON User.accountId = Account.id WHERE Account.id = :id")
public Account getAccountById(@Bind("id") int id);
}
但当方法有一个对象作为返回值(帐户代替列表<帐户>)似乎无法访问Mapper类中resultSet的多行。我能找到的唯一解决方案是在https://groups.google.com/d/msg/jdbi/4e4EP-gVwEQ/02CRStgYGtgJ中描述的,但那个解决方案也只能返回一个Set,其中有一个看起来不太优雅的对象。 (并且不能被资源类正确使用。)
似乎有一种方法在流利的API中使用了Folder2。但我不知道如何正确地将它与dropwizard集成在一起,而且我更愿意按照dropwizard文档中的建议坚持JDBI的SQL对象API。
真的没有办法在JDBI中使用SQL对象API获得一对多映射吗?对于一个数据库来说,这是一个基本的用例,我认为我必须错过一些东西。
所有帮助是极大的赞赏,
蒂尔曼
您可以通过简单地将其抽象为第一个选项移动到DAO类。看到这个答案:http://stackoverflow.com/a/26831146/846644 – Natan
这是一个非常好的mapper技巧!我在DAO方法中添加了一个注释和一个解决列表/非列表返回类型的方法,因为它引起了我的不安。 –
这里值得注意的是,第二个选项可能根本不是线程安全的(由于父母Account对象),除非您知道JDBI每次执行查询时都使用此ResultSetMapper的新实例,我真的不知道,但仍然认为依赖脆弱的假设。 – Hesham