本文将带您浏览和比较最受欢迎Java数据库访问框架(DAO层)。
ResultSet rs = stmt.executeQuery("SELECT id, name FROM Employees");
while(rs.hasNext()){
log.info("Employee id: " + rs.getInt("id") + " has name: " + rs.getString("name"));
}
User user = jdbc.qeuryForObject("SELECT * FROM USERS WHERE ID = ?", 1, User.class);
UserRecord user = new UserRecord();user.setId(1);user.setName("Peter");Result<UserRecord> books1 = DSL.using(configuration) .selectFrom(USERS) .where(condition(user)) .fetch();
public interface BlogMapper {
3
@Select('SELECT * FROM blog WHERE id = #{id}')
Blog selectBlog(int id);
}
// 获取数据
BlogMapper mapper = session.getMapper(BlogMapper.class);
Blog blog = mapper.selectBlog(101);" data-wx-hl-lang="Java" data-wx-hl-style="atom-one-dark">// Bean映射
public interface BlogMapper {
3
@Select("SELECT * FROM blog WHERE id = #{id}")
Blog selectBlog(int id);
}
// 获取数据
BlogMapper mapper = session.getMapper(BlogMapper.class);
Blog blog = mapper.selectBlog(101);
@Data // 这不是hibernate注解,而是lombok getter/setter@Entity@Table(name = "USERS")public class User { @Id @Column(name = "id") private Integer id; @Column(name = "name") private String name;}
User oldUser = (User) session.get(User.class, 1); //get user
User newUser = new User(123,'John');
session.save(developer); //add user
//HQL 示例
Query query = session.createQuery('FROM Users');
List users = query.list();" data-wx-hl-lang="Java" data-wx-hl-style="atom-one-dark">Session session = sessionFactory.openSession(); User oldUser = (User) session.get(User.class, 1); //get user User newUser = new User(123,"John"); session.save(developer); //add user //HQL 示例 Query query = session.createQuery("FROM Users"); List users = query.list();
// 只需要实现CrudRepository interfacepublic interface UserRepository extends CrudRepository<User, Long> { User findByName(String name); User findById(long id); @Query("SELECT u.ID FROM USERS u WHERE like ?1") //自定义表达式 List<Integer> findByUserName(String name);}// 查询示例User johnUser = userRepository.findByName("John");User johnUser = userRepository.findById(id);List<Integer> usersIdsWithOVPostfix = userRepository.findByUserName("%OV%");
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/258476.html