>解锁数据层的利弊,缺点和秘密调味料 在使用spring boot构建java应用程序时,在和 jdbc 之间进行选择,就像在瑞士军刀和手术刀之间挑选。这两种工具都与数据库互动,但它们以不同的方式解决问题。让我们阐述他们的优势,劣势和理想用例,其中有实际例子。
1。有什么区别?
public class userjdbcdao {
@autowired
private jdbctemplate jdbctemplate;
public user findbyid(long id) {
string sql = "select id, name, email from users where id = ?";
return jdbctemplate.queryforobject(sql, new object[]{id}, (rs, rownum) ->
new user(
rs.getlong("id"),
rs.getstring("name"),
rs.getstring("email")
));
}
}
pros:>最小的开销。
@entity
@table(name = "users")
public class user {
@id
@generatedvalue(strategy = generationtype.identity)
private long id;
private string name;
private string email;
// getters, setters, constructors
}
public interface userrepository extends jparepository {
// auto-implemented method: findbyemail(string email)
}
// usage
user user = userrepository.findbyid(1l).orelsethrow();
cons:
public listfindorderswithproducts(long userid) { string sql = """ select o.id, p.name, p.price from orders o join order_items oi on o.id = oi.order_id join products p on oi.product_id = p.id where o.user_id = ? """; return jdbctemplate.query(sql, new object[]{userid}, (rs, rownum) -> new order( rs.getlong("id"), rs.getstring("name"), rs.getdouble("price") )); }
jpa的解决方法(jpql或本机查询)>
@query(value = """
select new com.example.orderprojection(o.id, p.name, p.price)
from order o
join o.products p
where o.user.id = :userid
""", nativequery = false)
list findordersbyuser(@param("userid") long userid);
>
>
>通过嵌套关系管理用户资料,帖子和评论的社交媒体平台。
>在sql最重要的情况下,将jdbc用于其余20%。
标准
jdbc
弹簧数据jpa
speed
更快(raw sql,no orm开销)
稍慢(对象映射)
样本
更多(手动映射)
少(存储库抽象)
复杂查询
完全控制
受jpql/hibernate 限制
交易
手册(@transactional)
自动(存储库方法)
架构更改
sql更新
hibernate ddl自动上升(风险!)
criteria
jdbc
spring data jpa
speed
faster (raw sql, no orm overhead)
slightly slower (object mapping)
boilerplate
more (manual mapping)
less (repository abstraction)
complex queries
full control
limited by jpql/hibernate
transactions
manual (@transactional)
automatic (repository methods)
schema changes
sql updates required
hibernate ddl auto-update (risky!)
4。什么时候使用?
如果:,请选择jdbc
您需要在sql上
>用例:
选择弹簧数据jpa,如果:
快速开发繁重的应用程序
>混合方法:两者都混合!
>
组合基本操作的jpa和用于复杂查询的jdbc:>
public class UserService {
@Autowired
private UserRepository userRepository; // JPA
@Autowired
private UserJdbcDao userJdbcDao; // JDBC
public UserStats getUserStats(Long userId) {
User user = userRepository.findById(userId).orElseThrow();
List
5。判决
对于标准用例,春季数据jpa
是您的生产力促进
>从jpa开始的80%的应用程序。