为了复制这个用例,我SQLServerEscapeQuestionCharacterTest
在我的high-performance-java-persistence
GitHub 存储库中创建了。
假设您有以下 JPA 实体:
@Entity(name = "Post")
@Table(name = "[post]")
public static class Post {
@Id
private Long id;
private String title;
@Column(name = "[active?]")
private boolean active;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
}
与以下数据库表相关联:
CREATE TABLE [post] (
id bigint not null,
[active?] bit,
title varchar(255),
PRIMARY KEY (id)
)
如果您创建以下Post
实体:
Post post = new Post();
post.setId(1L);
post.setTitle("High-Performance Java Persistence");
post.setActive(true);
entityManager.persist(post);
Hibernate 将执行正确的 INSERT 语句:
INSERT INTO [post] (
[active?],
title,
id
)
VALUES (
true,
'High-Performance Java Persistence',
1
)
执行 JPQL 查询时:
List<Post> posts = entityManager
.createQuery(
"select p " +
"from Post p " +
"where p.active = :active", Post.class)
.setParameter("active", true)
.getResultList();
assertEquals(1, posts.size());
Hibernate 使用name
JPA 的属性,@Column
它已经转义了列名:
SELECT p.id AS id1_0_,
p.[active?] AS active2_0_,
p.title AS title3_0_
FROM [post] p
WHERE p.[active?] = true
对于原生 SQL 查询,您需要?
像这样对字符进行转义:
List<String> posts = entityManager
.createNativeQuery(
"select p.title " +
"from [post] p " +
"where p.[active\\?] = :active")
.setParameter("active", true)
.getResultList();
assertEquals(1, posts.size());
而且,它就像一个魅力。