10

我不是在寻找像 Hibernate 这样的持久层,我只想生成 SQL 字符串,它们应该与PreparedStatement. 我试过像Squiggle这样的库,但它只支持SELECT,我还想生成插入和更新。理想的用法是:

generateInsertOn("myTable").addValue("value1").addValue("value2").generate();

这将生成这个字符串:

"INSERT INTO myTable (value1, value2) VALUES(?, ?)"

我知道存在与我很相似的问题,例如this,但他们提出的问题与我不同。

4

3 回答 3

13

对于任意 SQL,请使用jOOQ。jOOQ 目前支持SELECT, INSERT, UPDATE, DELETE, TRUNCATE, 和MERGE. 您可以像这样创建 SQL:

// Since you're not executing the SQL, set connection to null
Connection connection = null;
Factory create = new MySQLFactory(connection);
String sql1 = create.select(A, B, C)
                    .from(MY_TABLE)
                    .where(A.equal(5))
                    .and(B.greaterThan(8))
                    .getSQL();

String sql2 = create.insertInto(MY_TABLE)
                    .values(A, 1)
                    .values(B, 2)
                    .getSQL();

String sql3 = create.update(MY_TABLE)
                    .set(A, 1)
                    .set(B, 2)
                    .where(C.greaterThan(5))
                    .getSQL();

支持的语法非常丰富。您还将找到对诸如ON DUPLICATE KEY UPDATE, FOR UPDATE,LOCK IN SHARE MODE等子句的支持。

有关更多详细信息,请参阅

http://www.jooq.org

(免责声明,我在 jOOQ 背后的公司工作)

于 2011-08-09T06:31:36.300 回答
3

您应该明确地看看SQLBuilder。它允许使用非常流畅的 API 生成简单但完整的 SQL。

于 2011-08-08T14:01:24.343 回答
0

在这里一筹莫展,你考虑过 iBatis 吗?这是一个真正脚踏实地的查询映射框架(我不愿以某种方式称其为 ORM 框架)。您必须像这样创建 XML 文件:

<mapper namespace="org.mybatis.jpetstore.persistence.ProductMapper">    
  <cache />    
  <select id="getProduct" parameterType="string" resultType="Product">
    SELECT
      PRODUCTID,
      NAME,
      DESCN as description,
      CATEGORY as categoryId
    FROM PRODUCT
    WHERE PRODUCTID = #{productId}
  </select>   
</mapper>

它连接了一个像这样的映射器:

public interface ProductMapper {
  Product getProduct(String productId);
}

它允许您从以下服务访问数据:

  @Autowired
  private ProductMapper productMapper;  

  public Product getProduct(String productId) {
    return productMapper.getProduct(productId);
  }

您可以使用 Spring 连接:

<!-- enable autowire -->
<context:annotation-config />

<!-- enable transaction demarcation with annotations -->
<tx:annotation-driven />

<!-- define the SqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="typeAliasesPackage" value="org.mybatis.jpetstore.domain" />
</bean>

<!-- scan for mappers and let them be autowired -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="org.mybatis.jpetstore.persistence" />
</bean>

另请参阅完整的 petstore 示例

我不是 iBatis 的明确粉丝,但它可能适合您在这种特定情况下的需求。

于 2011-08-09T08:36:52.837 回答