db user\u db和table user\u table中的我的第一个实体
public class User {
private int userId;
private String surname;
private String name;
//getters setters
public User(ResultSet resultSet){}
public User(ResultSet resultSet) throws SQLException {
setUserId(resultSet.getInt("userId"));
setSurname(resultSet.getString("surname"));
setName(resultSet.getString("name"));
}
}
它的存储库
public class UserRepository {
@Autowired
private DataBaseUtil dataBaseUtil;
public User findUser (int userId) throws SQLException {
String query = "SELECT "+
"surname, name, userId" +
"FROM "+
"user_db:user_table, "+
"WHERE "+
"userId = '" + userId + "'";
User currentUser = null;
try {
ResultSet resultSet = dataBaseUtil.getResultSet(query);
while (resultSet.next()) {
currentUser = new User(resultSet);
}
}
finally {
dataBaseUtil.closeConnection();
}
return currentUser;
}
}
我的数据库util
@Service
public class DataBaseUtil {
@Autowired
private DataSource dataSource;
private Connection connection;
private Statement statement;
private ResultSet resultSet;
public DataBaseUtil() {}
public DataBaseUtil getResultSet (String query) throws SQLException {
this.connection = dataSource.getConnection();
this.statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
this.resultSet = statement.executeQuery(query);
return this;
}
public void closeConnection() throws SQLException {
try (Connection connection = this.getConnection();
Statement statement = this.getStatement();
ResultSet resultSet = this.getResultSet()) {
}
}
public void update(String updateQuery) throws SQLException {
try (Connection connection = dataSource.getConnection();
Statement statement = connection.createStatement() ){
statement.executeUpdate(updateQuery);
}
}
}
好 啊。过了一段时间。我们已经创建了一个新表-user\u detail\u table
我正在创建实体
//My 2nd entity from db user_db and user_detail_table
public class UserDetail {
private int userId;
private String address;
private String hobby;
//setters getters
public UserDetail(ResultSet resultSet) throws SQLException {
setAddress(resultSet.getString("address"));
setHobby(resultSet.getString("hobby"));
setUserId(resultSet.getInt("userId"));
}
}
如果我想从user和userdetail获取数据,我应该怎么做(就像冬眠一样?我的想法:
我在用户实体中添加了userdetail字段。没关系,我想。。。这里我有问题:如果我把userrepository方法public user finduser(int userid)中的字符串查询改为
String query = "SELECT surname, name, address, hobby
"FROM user_db:user_table AS a, user_db:user_detail_table AS b"+
"WHERE a.userId = b.userId AND a.userId = '" + userId + "'";
看起来不错,但如果我只需要用户详细信息数据呢?我应该创建userdetailrepository,对吗?如果我只需要用户数据…我创建新方法?然后新的表将被再次创建,我们将需要“连接”它再次到用户…我们应该如何进行实体Map。如果我只需要用户数据的话,llooks将如何处理存储库?如果我需要用户和用户详细信息数据)?
对不起,我没有明确的描述问题…我希望你能理解我想要的:正确设计。。。最佳实践。如果你对我的代码有什么意见,我会很高兴听到的。非常感谢
暂无答案!
目前还没有任何答案,快来回答吧!