Domanda

C'è modo di creare query SQL al volo con MyBatis?Per concretizzare: ho una query, dove parte di esso (ma non parametro) deve essere creato nel runtime:

         with dummy (id) as (
           values (#{rangeEnd}) union all
           select id - 1 from dummy where id - 1 >= #{rangeStart}   
         ).......
.

La seconda parte può essere utilizzata come parametro, ma, quando si prova la query come posso ottenere un'eccezione:

[SQL0584] NULL or parameter marker in VALUES not allowed.
.

Con JDBC normale I Uso MessageFormat:

PreparedStatement ps = connection.prepareStatement(
            MessageFormat.format(MY_QUERY, currentRange.getRangeEnd()))
.

, ma non ho trovato un modo come farlo con mybatis.

È stato utile?

Soluzione

È davvero facile (risposta da Dynamic Seleziona istruzioni SQL con MyBatis ):

with dummy (id) as (
           values (${rangeEnd}) union all
           select id - 1 from dummy where id - 1 >= #{rangeStart}   
         ).......
.

Altri suggerimenti

Utilizzare Annotazione @SelectProvider:

public interface SqlMapper {
    static class PureSqlProvider {
        public String sql(String sql) {
           // Create your query here
           return sql; 
        }
    }

    @SelectProvider(type = PureSqlProvider.class, method = "sql")
    public List<Dummy> select(String sql);
}
.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top