-
Notifications
You must be signed in to change notification settings - Fork 10
/
PersonRepository.java
90 lines (70 loc) · 2.71 KB
/
PersonRepository.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package co.streamx.fluent.JPA.repository;
import static co.streamx.fluent.SQL.Directives.viewOf;
import static co.streamx.fluent.SQL.MySQL.SQL.LAST_INSERT_ID;
import static co.streamx.fluent.SQL.SQL.FROM;
import static co.streamx.fluent.SQL.SQL.INSERT;
import static co.streamx.fluent.SQL.SQL.SELECT;
import static co.streamx.fluent.SQL.SQL.VALUES;
import static co.streamx.fluent.SQL.SQL.WHERE;
import static co.streamx.fluent.SQL.SQL.row;
import java.util.List;
import javax.persistence.EntityManager;
import co.streamx.fluent.notation.Function;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import co.streamx.fluent.JPA.FluentJPA;
import co.streamx.fluent.JPA.FluentQuery;
import co.streamx.fluent.JPA.repository.entities.Person;
import co.streamx.fluent.functions.Consumer1;
@Repository
public interface PersonRepository extends CrudRepository<Person, Long>, EntityManagerSupplier {
default List<Person> getAllByName(String name) {
Consumer1<Person> sql = (Person p) -> {
SELECT(p);
FROM(p);
};
FluentQuery query = FluentJPA.SQL((Person p) -> {
sql.accept(p);
WHERE(p.getName() == name);
});
System.out.println(query);
return query.createQuery(getEntityManager(), Person.class).getResultList();
}
default List<Person> getAll() {
EntityManager em = getEntityManager();
return em.createQuery("select p from Person p", Person.class).getResultList();
}
default List<Person> getAllNative() {
FluentQuery query = FluentJPA.SQL((Person p) -> {
SELECT(p);
FROM(p);
});
return query.createQuery(getEntityManager(), Person.class).getResultList();
}
@Function(
underscoresAsBlanks = false
)
static long SCOPE_IDENTITY() {
throw new UnsupportedOperationException();
}
default Person insertDefault(String name,
int age) {
FluentQuery query = FluentJPA.SQL((Person p) -> {
INSERT().INTO(viewOf(p, Person::getName, Person::getAge));
VALUES(row(name, age));
// RETURNING(p); //PostgreSQL
// Person inserted = INSERTED(); //SQL Server
// OUTPUT(inserted);
});
int nOfUpdated = query.createQuery(getEntityManager()).executeUpdate();
if (nOfUpdated <= 0)
return null;
query = FluentJPA.SQL((Person p) -> {
SELECT(p);
FROM(p);
WHERE(p.getId() == SCOPE_IDENTITY());
});
Person person = query.createQuery(getEntityManager(), Person.class).getSingleResult();
return person;
}
}