盘点 Java 数据库访问框架——究竟哪个更适合你
来自投稿 编译:覃佑桦 https://dzone.com/articles/what-java-dao-layer-is-best-for-your-project
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();
// 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;
}
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 interface
public 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%");
相关文章