Cette feuille de triche est destinée à ** l'API Criteria pour Java **. Pour la version Kotlin de la feuille de triche, voir Introduction à la feuille de contrôle de l'API des critères Doma-Kotlin.
La version de Doma est 2.43.0. Pour un aperçu de l'API Criteria, voir Introduction à Doma. La version de Java que j'utilise est la 8.
Supposons que les classes d'entités ʻEmployee et
Department` soient définies.
De plus, on suppose que les variables suivantes sont définies.
Entityql entityql = new Entityql(config);
Nativesql nativeSql = new NativeSql(config);
Employee_ e = new Employee_();
Department_ d = new Department_();
L'exemple SQL peut différer de ce qui est réellement généré.
Tuple2
etc.)List<Employee> list = entityql.from(e).fetch();
// select * from employee t0_
Renvoie null s'il n'existe pas.
Employee employee = entityql.from(e).where(c -> c.eq(e.id, 1)).fetchOne();
// select * from employee t0_ where t0_.id = ?
S'il n'existe pas, il renvoie ʻOptional.empty () `.
Optional<Employee> employee = entityql.from(e).where(c -> c.eq(e.id, 1)).fetchOptional();
// select * from employee t0_ where t0_.id = ?
Traitez de grandes quantités de données une par une sans réduire la mémoire.
String names = nativeSql.from(e).mapStream(stream ->
stream.map(Employee::getName).collect(Collectors.joining(","))
);
// select * from employee t0_
Raccourci de recherche de flux.
Map<Integer, List<Employee>> map = nativeSql.from(e).collect(Collectors.groupingBy(Employee::getDepartmentId));
// select * from employee t0_
Ce qui précède est équivalent au code ci-dessous.
Map<Integer, List<Employee>> map = nativeSql.from(e).mapStream(stream ->
stream.collect(Collectors.groupingBy(Employee::getDepartmentId))
);
// select * from employee t0_
Renvoie le résultat sous forme de classe tapple.
List<Tuple2<String, Integer>> list = nativeSql.from(e).select(e.name, e.age).fetch();
// select t0_.name, t0_.age from employee t0_
Renvoie le résultat sous forme de classe d'entité. La clé primaire est toujours incluse dans la clause SELECT et est également définie dans l'entité.
List<Employee> list = entityql.from(e).selectTo(e, e.name, e.age).fetch();
// select t0_.id, t0_.name, t0_.age from employee t0_
List<Employee> list = entityql.from(e).orderBy(c -> {
c.asc(e.name);
c.desc(e.age);
}).fetch();
// select * from employee t0_ order by t0_.name asc, t0_.age desc
List<String> list = nativeSql.from(e).distinct().select(e.name).fetch();
// select distinct t0_.name from employee t0_
Limit/Offset
List<Employee> list = entityql.from(e).limit(10).offset(3).fetch();
// select * from employee t0_ limit 10 offset 3
List<Employee> list = entityql.from(e).forUpdate().fetch();
// select * from employee t0_ for update
Comme fonction d'agrégation, ʻavg,
count,
countDistinct,
max,
min,
sum définis dans ʻorg.seasar.doma.jdbc.criteria.expression.Expressions
peuvent être utilisés. ..
Integer integer = nativeSql.from(e).select(Expressions.sum(e.age)).fetchOne();
// select sum(t0_.age) from employee t0_
List<Tuple2<Integer, Long>> list = nativeSql.from(e).groupBy(e.departmentId).select(e.departmentId, Expressions.count()).fetch();
// select t0_.department_id, count(*) from employee t0_ group by t0_.department_id
Lorsque la méthode groupBy
n'est pas appelée, la colonne requise pour la clause GROUP BY est déduite de la propriété spécifiée dans la méthode select
et attribuée automatiquement. Par conséquent, le code suivant générera un SQL équivalent à ce qui précède.
List<Tuple2<Integer, Long>> list = nativeSql.from(e).select(e.departmentId, Expressions.count()).fetch();
// select t0_.department_id, count(*) from employee t0_ group by t0_.department_id
//Trouvez le nombre d'employés dans chaque service pour les services de plus de 3 employés
List<Tuple2<Long, String>> list =
nativeSql
.from(e)
.innerJoin(d, on -> on.eq(e.departmentId, d.id))
.having(c -> c.gt(Expressions.count(), 3L))
.select(Expressions.count(), d.name)
.fetch();
// select count(*), t1_.name from employee t0_ inner join department t1_ on (t0_.department_id = t1_.id) group by t1_.name having count(*) > 3
Seule la jointure interne est effectuée.
List<Employee> list = entityql.from(e).innerJoin(d, on -> on.eq(e.departmentId, d.id)).fetch();
// select t0_.* from employee t0_ inner join department t1_ on (t0_.department_id = t1_.id)
Joindre interne et obtenir des entités associées.
List<Employee> list = entityql.from(e).innerJoin(d, on -> on.eq(e.departmentId, d.id)).associate(e, d, (employee, department) {
employee.setDepartment(department);
department.getEmployees().add(employee);
}).fetch();
// select * from employee t0_ inner join department t1_ on (t0_.department_id = t1_.id)
Seule la jointure externe est effectuée.
List<Employee> list = entityql.from(e).leftJoin(d, on -> on.eq(e.departmentId, d.id)).fetch();
// select t0_.* from employee t0_ left outer join department t1_ on (t0_.department_id = t1_.id)
Rejoignez et obtenez également des entités associées.
List<Employee> list = entityql.from(e). leftJoin(d, on -> on.eq(e.departmentId, d.id)).associate(e, d, (employee, department) {
employee.setDepartment(department);
department.getEmployees().add(employee);
}).fetch();
// select * from employee t0_ left outer join department t1_ on (t0_.department_id = t1_.id)
Vous pouvez joindre (auto-jointure) les mêmes tables en utilisant différentes instances du même métamodèle.
Employee_ m = new Employee_();
List<Employee> list = entityql.from(e).leftJoin(m, on -> on.eq(e.managerId, m.id)).fetch();
// select t0_.* from employee t0_ left outer join employee t1_ on (t0_.manager_id = t1_.id)
Vous pouvez également obtenir des entités associées.
Employee_ m = new Employee_();
List<Employee> list = entityql.from(e).leftJoin(m, on -> on.eq(e.managerId, m.id)).associate(e, m, (employee, manager) {
employee.setManager(manager);
}).fetch();
// select * from employee t0_ left outer join employee t1_ on (t0_.manager_id = t1_.id)
UNION
List<Tuple2<Integer, String>> list =
nativeSql
.from(e)
.select(e.id, e.name)
.union(nativeSql.from(d).select(d.id, d.name))
.fetch();
// select t0_.id, t0_.name from employee t0_ union select t0_.id, t0_.name from department t0_
Pour trier, spécifiez la colonne cible par index. l'index commence à 1.
List<Tuple2<Integer, String>> list =
nativeSql
.from(e)
.select(e.id, e.name)
.union(nativeSql.from(d).select(d.id, d.name))
.orderBy(c -> c.asc(2))
.fetch();
// (select t0_.id, t0_.name from employee t0_) union (select t0_.id, t0_.name from department t0_) order by 2 asc
Vous pouvez également UNION ALL.
List<Tuple2<Integer, String>> list =
nativeSql
.from(e)
.select(e.id, e.name)
.unionAll(nativeSql.from(d).select(d.id, d.name))
.fetch();
// select t0_.id, t0_.name from employee t0_ union all select t0_.id, t0_.name from department t0_
Employee employee = ...;
entityql.insert(e, employee).execute();
// insert into employee (id, name, age, version) values (?, ?, ?, ?)
List<Employee> employees = ...;
entityql.insert(e, employees).execute();
// insert into employee (id, name, age, version) values (?, ?, ?, ?)
Ajout de plusieurs éléments à une autre table avec la même structure de données.
Department_ da = new Department_("DEPARTMENT_ARCHIVE");
nativeSql.insert(da).select(c -> c.from(d).where(cc -> cc.in(d.id, Arrays.asList(1, 2)))).execute();
// insert into department_archive (id, name, version) select t0_.id, t0_.name, t0_.version from department t0_ where t0_.id in (1, 2)
Employee employee = ...;
entityql.update(e, employee).execute();
// update employee set name = ?, age = ?, version = ? + 1 where id = ? and version = ?
List<Employee> employees = ...;
entityql.update(e, employees).execute();
// update employee set name = ?, age = ?, version = ? + 1 where id = ? and version = ?
nativeSql
.update(e)
.set(c -> c.value(e.departmentId, 3))
.where(
c -> {
c.eq(e.managerId, 3);
c.lt(e.age, 30);
})
.execute();
// update employee t0_ set department_id = ? where t0_.manager_id = ? and t0_.age < ?
nativeSql
.update(e)
.set(c -> {
c.value(e.name, Expressions.concat("[", Expressions.concat(e.name, "]")));
c.value(e.age, Expressions.add(e.age, 1));
})
.where(c -> c.eq(e.id, 1))
.execute();
// update employee t0_ set name = concat(?, concat(t0_.name, ?)), age = (t0_.age + ?) where t0_.id = ?
Employee employee = ...;
entityql.delete(e, employee).execute();
// delete from employee where id = ? and version = ?
List<Employee> employees = ...;
entityql.delete(e, employees).execute();
// delete from employee where id = ? and version = ?
nativeSql.delete(e).where(c -> c.ge(e.age, 50)).execute();
// delete from employee t0_ where t0_.age >= ?
=
entityql.from(e).where(c -> c.eq(e.age, 20)).fetch();
// select * from employee t0_ where t0_.age = ?
<>
entityql.from(e).where(c -> c.ne(e.age, 20)).fetch();
// select * from employee t0_ where t0_.age <> ?
entityql.from(e).where(c -> c.gt(e.age, 20)).fetch();
// select * from employee t0_ where t0_.age > ?
=
entityql.from(e).where(c -> c.ge(e.age, 20)).fetch();
// select * from employee t0_ where t0_.age >= ?
<
entityql.from(e).where(c -> c.lt(e.age, 20)).fetch();
// select * from employee t0_ where t0_.age < ?
<=
entityql.from(e).where(c -> c.le(e.age, 20)).fetch();
// select * from employee t0_ where t0_.age <= ?
IS NULL
entityql.from(e).where(c -> c.isNull(e.age)).fetch();
// select * from employee t0_ where t0_.age is null
IS NOT NULL
entityql.from(e).where(c -> c.isNotNull(e.age)).fetch();
// select * from employee t0_ where t0_.age is not null
Generate = si ʻage` n'est pas nul.
entityql.from(e).where(c -> c.eqOrIsNull(e.age, age)).fetch();
// select * from employee t0_ where t0_.age = ?
Générer IS NULL si ʻage` est nul.
entityql.from(e).where(c -> c.eqOrIsNull(e.age, age)).fetch();
// select * from employee t0_ where t0_.age is null
Génère <> si ʻage` n'est pas nul.
entityql.from(e).where(c -> c.neOrIsNotNull(e.age, age)).fetch();
// select * from employee t0_ where t0_.age <> ?
Generate IS NOT NULL si ʻage` est nul.
entityql.from(e).where(c -> c.neOrIsNotNull(e.age, age)).fetch();
// select * from employee t0_ where t0_.age is not null
LIKE
Un prédicat LIKE qui ne traite rien.
entityql.from(e).where(c -> c.like(e.name, "A%")).fetch();
// select * from employee t0_ where t0_.name like ?
// select * from employee t0_ where t0_.name like 'A%' (SQL valorisé lié)
LIKE prédicat pour la correspondance de préfixe. Les caractères génériques sont échappés.
entityql.from(e).where(c -> c.like(e.name, "A%", LikeOption.prefix())).fetch();
// select * from employee t0_ where t0_.name like ? escape '$'
// select * from employee t0_ where t0_.name like 'A$%%' escape '$' (SQL valorisé lié)
LIKE prédicat pour correspondance intermédiaire. Les caractères génériques sont échappés.
entityql.from(e).where(c -> c.like(e.name, "A%", LikeOption.infix())).fetch();
// select * from employee t0_ where t0_.name like ? escape '$'
// select * from employee t0_ where t0_.name like '%A$%%' escape '$' (SQL valorisé lié)
LIKE prédicat pour la correspondance de suffixe. Les caractères génériques sont échappés.
entityql.from(e).where(c -> c.like(e.name, "A%", LikeOption.suffix())).fetch();
// select * from employee t0_ where t0_.name like ? escape '$'
// select * from employee t0_ where t0_.name like '%A$%' escape '$' (SQL valorisé lié)
NOT LIKE
PAS COMME prédicat sans aucun traitement.
entityql.from(e).where(c -> c.notLike(e.name, "A%")).fetch();
// select * from employee t0_ where t0_.name not like ?
// select * from employee t0_ where t0_.name not like 'A%' (SQL valorisé lié)
NOT LIKE prédicat pour la correspondance de préfixe. Les caractères génériques sont échappés.
entityql.from(e).where(c -> c.notLike(e.name, "A%", LikeOption.prefix())).fetch();
// select * from employee t0_ where t0_.name not like ? escape '$'
// select * from employee t0_ where t0_.name not like 'A$%%' escape '$' (SQL valorisé lié)
NOT LIKE prédicat pour une correspondance intermédiaire. Les caractères génériques sont échappés.
entityql.from(e).where(c -> c.notLike(e.name, "A%", LikeOption.infix())).fetch();
// select * from employee t0_ where t0_.name not like ? escape '$'
// select * from employee t0_ where t0_.name not like '%A$%%' escape '$' (SQL valorisé lié)
NOT LIKE prédicat pour la correspondance de suffixe. Les caractères génériques sont échappés.
entityql.from(e).where(c -> c.notLike(e.name, "A%", LikeOption.suffix())).fetch();
// select * from employee t0_ where t0_.name not like ? escape '$'
// select * from employee t0_ where t0_.name not like '%A$%' escape '$' (SQL valorisé lié)
BETWEEN
entityql.from(e).where(c -> c.between(e.age, 20, 30)).fetch();
// select * from employee t0_ where t0_.age between ? and ?
IN
Un simple prédicat IN.
entityql.from(e).where(c -> c.in(e.age, Arrays.asList(10, 20))).fetch();
// select * from employee t0_ where t0_.age in (?, ?)
IN prédicat utilisant tapple.
entityql.from(e).where(c -> c.in(new Tuple2(e.age, e.salary), Arrays.asList(new Tuple2(10, 1000), new Tuple2(20, 2000)))).fetch();
// select * from employee t0_ where (t0_.age, t0_.salary) in ((?, ?), (?, ?))
IN prédicat avec sous-requête.
entityql.from(e).where(c -> c.in(e.departmentId, c.from(d).select(d.id))).fetch();
// select * from employee t0_ where t0_.department_id in (select t1_.id from department t1_)
NOT IN
Un simple prédicat NOT IN.
entityql.from(e).where(c -> c.notIn(e.age, Arrays.asList(10, 20))).fetch();
// select * from employee t0_ where t0_.age not in (?, ?)
NOT IN prédicat utilisant tapple.
entityql.from(e).where(c -> c.notIn(new Tuple2(e.age, e.salary), Arrays.asList(new Tuple2(10, 1000), new Tuple2(20, 2000)))).fetch();
// select * from employee t0_ where (t0_.age, t0_.salary) not in ((?, ?), (?, ?))
NOT IN prédicat avec sous-requête.
entityql.from(e).where(c -> c.notIn(e.departmentId, c.from(d).select(d.id))).fetch();
// select * from employee t0_ where t0_.department_id not in (select t1_.id from department t1_)
EXISTS
entityql.from(e).where(c -> c.exists(c.from(d).where(c2 -> c2.eq(e.departmentId, d.id))).fetch();
// select * from employee t0_ where exists (select * from department t1_ where t0_.deparment_id = t1_.id)
AND
entityql.from(e).where(c -> {
c.eq(e.age, 20);
c.ge(e.salary, 100000);
c.lt(e.salary, 200000);
}).fetch();
// select * from employee t0_ where t0_.age = ? and t0_.salary >= ? and t0_.salary < ?
OR
entityql.from(e).where(c -> {
c.eq(e.age, 20);
c.or(() -> {
c.ge(e.salary, 100000);
c.lt(e.salary, 200000);
});
}).fetch();
// select * from employee t0_ where t0_.age = ? or (t0_.salary >= ? and t0_.salary < ?)
NOT
entityql.from(e).where(c -> {
c.eq(e.age, 20);
c.not(() -> {
c.ge(e.salary, 100000);
c.lt(e.salary, 200000);
});
}).fetch();
// select * from employee t0_ where t0_.age = ? and not (t0_.salary >= ? and t0_.salary < ?)
Incorporez la valeur dans SQL telle quelle sans utiliser de variables de liaison.
Seuls les types acceptés par la méthode litera
de ʻorg.seasar.doma.jdbc.criteria.expression.Expressions` sont pris en charge.
List<Employee> list = entityql.from(e).where(c -> c.eq(e.id, Expressions.literal(10))).fetch();
// select * from employee t0_ where t0_.id = 10
Pour les opérations arithmétiques, ʻadd,
sub,
mul,
div,
mod, etc. définis dans ʻorg.seasar.doma.jdbc.criteria.expression.Expressions
peuvent être utilisés.
List<String> list = nativeSql.from(e).select(Expressions.add(e.age, 10)).fetch();
// select (t0_.age + ?) from employee t0_
Les fonctions de chaîne incluent «concat», «lower», «up», «trim», «ltrim», «rtrim» définis dans «org.seasar.doma.jdbc.criteria.expression.Expressions». Peut être utilisé.
List<String> list = nativeSql.from(e).select(Expressions.lower(e.name)).fetch();
// select lower(t0_.name) from employee t0_
List<Tuple2<String, String>> list =
nativeSql
.from(e)
.select(
e.name,
Expressions.when(
c -> {
c.lt(e.age, Expressions.literal(10), Expressions.literal("A"));
c.lt(e.age, Expressions.literal(20), Expressions.literal("B"));
c.lt(e.age, Expressions.literal(30), Expressions.literal("C"));
},
Expressions.literal("D")))
.fetch();
// select t0_.name, case when t0_.age < 10 then 'A' when t0_.age < 20 then 'B' when t0_.age < 30 then 'C' else 'D' end from EMPLOYEE t0_
Recommended Posts