下面列出了javax.persistence.EntityManager#detach ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private File pickObject(String flag) throws Exception {
File o = this.business().entityManagerContainer().flag(flag, File.class);
if (o != null) {
this.entityManagerContainer().get(File.class).detach(o);
}
if (null == o) {
EntityManager em = this.entityManagerContainer().get(File.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<File> cq = cb.createQuery(File.class);
Root<File> root = cq.from(File.class);
Predicate p = cb.equal(root.get(File_.name), flag);
List<File> os = em.createQuery(cq.select(root).where(p).distinct(true)).getResultList();
if (os.size() == 1) {
o = os.get(0);
em.detach(o);
}
}
return o;
}
private File pickObject(String flag) throws Exception {
File o = this.business().entityManagerContainer().flag(flag, File.class);
if (o != null) {
this.entityManagerContainer().get(File.class).detach(o);
}
if (null == o) {
EntityManager em = this.entityManagerContainer().get(File.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<File> cq = cb.createQuery(File.class);
Root<File> root = cq.from(File.class);
Predicate p = cb.equal(root.get(File_.name), flag);
List<File> os = em.createQuery(cq.select(root).where(p).distinct(true)).getResultList();
if (os.size() == 1) {
o = os.get(0);
em.detach(o);
}
}
return o;
}
@Decision(PUT)
public Application update(ApplicationUpdateRequest updateRequest, Application application, EntityManager em) {
EntityTransactionManager tx = new EntityTransactionManager(em);
tx.required(() -> converter.copy(updateRequest, application));
em.detach(application);
return application;
}
private Identity pickObject(String flag) throws Exception {
Identity o = this.entityManagerContainer().flag(flag, Identity.class);
if (o != null) {
this.entityManagerContainer().get(Identity.class).detach(o);
} else {
String name = flag;
Matcher matcher = PersistenceProperties.Identity.distinguishedName_pattern.matcher(flag);
if (matcher.find()) {
name = matcher.group(1);
String unique = matcher.group(2);
o = this.entityManagerContainer().flag(unique, Identity.class);
if (null != o) {
this.entityManagerContainer().get(Identity.class).detach(o);
}
}
if (null == o) {
EntityManager em = this.entityManagerContainer().get(Identity.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Identity> cq = cb.createQuery(Identity.class);
Root<Identity> root = cq.from(Identity.class);
Predicate p = cb.equal(root.get(Identity_.name), name);
List<Identity> os = em.createQuery(cq.select(root).where(p).distinct(true)).getResultList();
if (os.size() == 1) {
o = os.get(0);
em.detach(o);
}
}
}
return o;
}
private PermissionSetting pickObject(String flag) throws Exception {
PermissionSetting o = this.entityManagerContainer().flag(flag, PermissionSetting.class);
if (o != null) {
this.entityManagerContainer().get(PermissionSetting.class).detach(o);
} else {
String name = flag;
Matcher matcher = PersistenceProperties.PermissionSetting.distinguishedName_pattern.matcher(flag);
if (matcher.find()) {
name = matcher.group(1);
String unique = matcher.group(2);
o = this.entityManagerContainer().flag(unique, PermissionSetting.class);
if (null != o) {
this.entityManagerContainer().get(PermissionSetting.class).detach(o);
}
}
if (null == o) {
EntityManager em = this.entityManagerContainer().get(PermissionSetting.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<PermissionSetting> cq = cb.createQuery(PermissionSetting.class);
Root<PermissionSetting> root = cq.from(PermissionSetting.class);
Predicate p = cb.equal(root.get(PermissionSetting_.id), name);
List<PermissionSetting> os = em.createQuery(cq.select(root).where(p).distinct(true)).getResultList();
if (os.size() == 1) {
o = os.get(0);
em.detach(o);
}
}
}
return o;
}
@SuppressWarnings("unchecked")
public <T extends JpaObject> List<T> listWithProcess(Class<T> clz, Process process) throws Exception {
List<T> list = new ArrayList<>();
Ehcache cache = ApplicationCache.instance().getCache(clz);
String cacheKey = ApplicationCache.concreteCacheKey("listWithProcess", process.getId(), clz.getName());
Element element = cache.get(cacheKey);
if (null != element) {
Object obj = element.getObjectValue();
if (null != obj) {
list = (List<T>) obj;
}
} else {
EntityManager em = this.entityManagerContainer().get(clz);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<T> cq = cb.createQuery(clz);
Root<T> root = cq.from(clz);
Predicate p = cb.equal(root.get(Agent.process_FIELDNAME), process.getId());
cq.select(root).where(p);
List<T> os = em.createQuery(cq).getResultList();
for (T t : os) {
em.detach(t);
list.add(t);
}
/* 将object改为unmodifiable */
list = Collections.unmodifiableList(list);
cache.put(new Element(cacheKey, list));
}
return list;
}
@SuppressWarnings("unchecked")
protected <T extends JpaObject> List<T> listWithCategory(Class<T> clz, CategoryInfo categoryInfo) throws Exception {
List<T> list = new ArrayList<>();
Ehcache cache = ApplicationCache.instance().getCache(clz);
String cacheKey = "listWithCategory#" + categoryInfo.getId() + "#" + clz.getName();
Element element = cache.get(cacheKey);
if (null != element) {
Object obj = element.getObjectValue();
if (null != obj) {
list = (List<T>) obj;
}
} else {
EntityManager em = this.entityManagerContainer().get(clz);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<T> cq = cb.createQuery(clz);
Root<T> root = cq.from(clz);
Predicate p = cb.equal(root.get("categoryInfo"), categoryInfo.getId());
cq.select(root).where(p);
List<T> os = em.createQuery(cq).getResultList();
for (T t : os) {
em.detach(t);
list.add(t);
}
/* 将object改为unmodifiable */
list = Collections.unmodifiableList(list);
cache.put(new Element(cacheKey, list));
}
return list;
}
private PersonCard pickObject(String flag) throws Exception {
PersonCard o = this.entityManagerContainer().flag(flag, PersonCard.class);
if (o != null) {
this.entityManagerContainer().get(PersonCard.class).detach(o);
} else {
String name = flag;
Matcher matcher = PersistenceProperties.PersonCard.distinguishedName_pattern.matcher(flag);
if (matcher.find()) {
name = matcher.group(1);
String unique = matcher.group(2);
o = this.entityManagerContainer().flag(unique, PersonCard.class);
if (null != o) {
this.entityManagerContainer().get(PersonCard.class).detach(o);
}
}
if (null == o) {
EntityManager em = this.entityManagerContainer().get(PersonCard.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<PersonCard> cq = cb.createQuery(PersonCard.class);
Root<PersonCard> root = cq.from(PersonCard.class);
Predicate p = cb.equal(root.get(PersonCard_.name), name);
List<PersonCard> os = em.createQuery(cq.select(root).where(p).distinct(true)).getResultList();
if (os.size() == 1) {
o = os.get(0);
em.detach(o);
}
}
}
return o;
}
private UnitAttribute pickObject(String flag) throws Exception {
UnitAttribute o = this.entityManagerContainer().flag(flag, UnitAttribute.class);
if (o != null) {
this.entityManagerContainer().get(UnitAttribute.class).detach(o);
} else {
String name = flag;
Matcher matcher = PersistenceProperties.UnitAttribute.distinguishedName_pattern.matcher(flag);
if (matcher.find()) {
name = matcher.group(1);
String unique = matcher.group(2);
o = this.entityManagerContainer().flag(unique, UnitAttribute.class);
if (null != o) {
this.entityManagerContainer().get(UnitAttribute.class).detach(o);
}
}
if (null == o) {
EntityManager em = this.entityManagerContainer().get(UnitAttribute.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<UnitAttribute> cq = cb.createQuery(UnitAttribute.class);
Root<UnitAttribute> root = cq.from(UnitAttribute.class);
Predicate p = cb.equal(root.get(UnitAttribute_.name), name);
List<UnitAttribute> os = em.createQuery(cq.select(root).where(p).distinct(true)).getResultList();
if (os.size() == 1) {
o = os.get(0);
em.detach(o);
}
}
}
return o;
}
@Decision(DELETE)
public Void delete(User user,
ActionRecord actionRecord,
UserPermissionPrincipal principal,
RestContext context,
EntityManager em) {
EntityTransactionManager tm = new EntityTransactionManager(em);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<UserProfileVerification> query = cb.createQuery(UserProfileVerification.class);
Root<UserProfileVerification> userProfileVerificationRoot = query.from(UserProfileVerification.class);
Join<UserProfileVerification, User> userJoin = userProfileVerificationRoot.join("user");
query.where(cb.equal(userJoin.get("id"), user.getId()));
config.getHookRepo().runHook(HookPoint.BEFORE_DELETE_USER, context);
tm.required(() -> {
em.createQuery(query)
.getResultStream()
.forEach(em::remove);
em.remove(user);
config.getHookRepo().runHook(HookPoint.AFTER_DELETE_USER, context);
});
actionRecord.setActionType(ActionType.USER_DELETED);
actionRecord.setActor(principal.getName());
actionRecord.setDescription(user.getAccount());
em.detach(user);
return null;
}
private Group pickObject(String flag) throws Exception {
Group o = this.entityManagerContainer().flag(flag, Group.class);
if (o != null) {
this.entityManagerContainer().get(Group.class).detach(o);
} else {
String name = flag;
Matcher matcher = group_distinguishedName_pattern.matcher(flag);
if (matcher.find()) {
name = matcher.group(1);
String unique = matcher.group(2);
o = this.entityManagerContainer().flag(unique, Group.class);
if (null != o) {
this.entityManagerContainer().get(Group.class).detach(o);
}
}
if (null == o) {
EntityManager em = this.entityManagerContainer().get(Group.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Group> cq = cb.createQuery(Group.class);
Root<Group> root = cq.from(Group.class);
Predicate p = cb.equal(root.get(Group_.name), name);
List<Group> os = em.createQuery(cq.select(root).where(p).distinct(true)).getResultList();
if (os.size() == 1) {
o = os.get(0);
em.detach(o);
}
}
}
return o;
}
private Person pickObject(String flag) throws Exception {
Person o = this.entityManagerContainer().flag(flag, Person.class);
if (o != null) {
this.entityManagerContainer().get(Person.class).detach(o);
} else {
String name = flag;
Matcher matcher = PersistenceProperties.Person.distinguishedName_pattern.matcher(flag);
if (matcher.find()) {
name = matcher.group(1);
String unique = matcher.group(2);
o = this.entityManagerContainer().flag(unique, Person.class);
if (null != o) {
this.entityManagerContainer().get(Person.class).detach(o);
}
}
if (null == o) {
EntityManager em = this.entityManagerContainer().get(Person.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Person> cq = cb.createQuery(Person.class);
Root<Person> root = cq.from(Person.class);
Predicate p = cb.equal(root.get(Person_.name), name);
List<Person> os = em.createQuery(cq.select(root).where(p).distinct(true)).getResultList();
if (os.size() == 1) {
o = os.get(0);
em.detach(o);
}
}
}
return o;
}
private UnitDuty pickObject(String flag) throws Exception {
UnitDuty o = this.entityManagerContainer().flag(flag, UnitDuty.class);
if (o != null) {
this.entityManagerContainer().get(UnitDuty.class).detach(o);
} else {
String name = flag;
Matcher matcher = unitDuty_distinguishedName_pattern.matcher(flag);
if (matcher.find()) {
name = matcher.group(1);
String unique = matcher.group(2);
o = this.entityManagerContainer().flag(unique, UnitDuty.class);
if (null != o) {
this.entityManagerContainer().get(UnitDuty.class).detach(o);
}
}
if (null == o) {
EntityManager em = this.entityManagerContainer().get(UnitDuty.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<UnitDuty> cq = cb.createQuery(UnitDuty.class);
Root<UnitDuty> root = cq.from(UnitDuty.class);
Predicate p = cb.equal(root.get(UnitDuty_.name), name);
List<UnitDuty> os = em.createQuery(cq.select(root).where(p).distinct(true)).getResultList();
if (os.size() == 1) {
o = os.get(0);
em.detach(o);
}
}
}
return o;
}
@Decision(POST)
public PasswordCredential create(PasswordCredentialCreateRequest createRequest,
User user,
UserPermissionPrincipal principal,
ActionRecord actionRecord,
RestContext context,
EntityManager em) {
String salt = RandomUtils.generateRandomString(16, config.getSecureRandom());
PasswordCredential passwordCredential = builder(new PasswordCredential())
.set(PasswordCredential::setUser, user)
.set(PasswordCredential::setSalt, salt)
.set(PasswordCredential::setInitial, createRequest.isInitial())
.set(PasswordCredential::setPassword, PasswordUtils.pbkdf2(createRequest.getPassword(), salt, 100))
.set(PasswordCredential::setCreatedAt, LocalDateTime.now())
.build();
EntityTransactionManager tx = new EntityTransactionManager(em);
tx.required(() -> {
em.persist(passwordCredential);
context.putValue(passwordCredential);
config.getHookRepo().runHook(AFTER_CREATE_PASSWORD_CREDENTIAL, context);
});
actionRecord.setActionType(ActionType.PASSWORD_CREATED);
actionRecord.setActor(principal.getName());
actionRecord.setDescription(user.getAccount());
em.detach(passwordCredential);
return passwordCredential;
}
@Decision(POST)
public Application create(ApplicationCreateRequest createRequest, EntityManager em) {
Application application = converter.createFrom(createRequest, Application.class);
application.setWriteProtected(false);
EntityTransactionManager tx = new EntityTransactionManager(em);
tx.required(() -> em.persist(application));
em.detach(application);
return application;
}
/**
* removes specific job from queue no matter what its current status is.
*
* @param action - the action class
* @param params - parameters to get jobs
* @return the number of jobs deleted
*/
public int remove(Class<? extends MCRJobAction> action, Map<String, String> params) {
if (!running) {
return 0;
}
EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
StringBuilder qStr = new StringBuilder("FROM MCRJob job WHERE action = '" + action.getName() + "' ");
for (String paramKey : params.keySet()) {
qStr.append(" AND job.parameters['")
.append(paramKey)
.append("'] = '")
.append(params.get(paramKey))
.append('\'');
}
Query query = em.createQuery(qStr.toString());
@SuppressWarnings("unchecked")
Iterator<MCRJob> results = query.getResultList().iterator();
if (!results.hasNext()) {
return 0;
}
MCRJob job = results.next();
try {
em.remove(job);
em.detach(job);
return 1;
} finally {
clearPreFetch();
}
}
@SuppressWarnings("unchecked")
protected <T extends JpaObject> List<T> listWithProcess(Class<T> clz, Process process) throws Exception {
List<T> list = new ArrayList<>();
Ehcache cache = ApplicationCache.instance().getCache(clz);
String cacheKey = "listWithProcess#" + process.getId() + "#" + clz.getName();
Element element = cache.get(cacheKey);
if (null != element) {
Object obj = element.getObjectValue();
if (null != obj) {
list = (List<T>) obj;
}
} else {
EntityManager em = this.entityManagerContainer().get(clz);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<T> cq = cb.createQuery(clz);
Root<T> root = cq.from(clz);
Predicate p = cb.equal(root.get("process"), process.getId());
cq.select(root).where(p);
List<T> os = em.createQuery(cq).getResultList();
for (T t : os) {
em.detach(t);
list.add(t);
}
/* 将object改为unmodifiable */
list = Collections.unmodifiableList(list);
cache.put(new Element(cacheKey, list));
}
return list;
}
@Decision(HANDLE_OK)
public Group find(Group group, EntityManager em) {
em.detach(group);
return group;
}
@MCRCommand(syntax = "generate md5sum files in directory {0}",
help = "writes md5sum files for every content store in directory {0}")
public static void writeMD5SumFile(String targetDirectory) throws IOException {
File targetDir = getDirectory(targetDirectory);
EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
MCRStreamQuery<MCRFSNODES> streamQuery = MCRStreamQuery.getInstance(em,
"from MCRFSNODES where type='F' order by storeid, storageid", MCRFSNODES.class);
Map<String, MCRContentStore> availableStores = MCRContentStoreFactory.getAvailableStores();
String currentStoreId = null;
MCRContentStore currentStore = null;
File currentStoreBaseDir = null;
BufferedWriter bw = null;
String nameOfProject = MCRConfiguration2.getString("MCR.NameOfProject").orElse("MyCoRe");
try {
Iterator<MCRFSNODES> fsnodes = streamQuery.getResultStream().iterator();
while (fsnodes.hasNext()) {
MCRFSNODES fsNode = fsnodes.next();
String storeID = fsNode.getStoreid();
String storageID = fsNode.getStorageid();
String md5 = fsNode.getMd5();
em.detach(fsNode);
if (!storeID.equals(currentStoreId)) {
//initialize current store
currentStoreId = storeID;
currentStore = availableStores.get(storeID);
if (bw != null) {
bw.close();
}
File outputFile = new File(targetDir,
new MessageFormat("{0}-{1}.md5", Locale.ROOT).format(new Object[] { nameOfProject, storeID }));
LOGGER.info("Writing to file: {}", outputFile.getAbsolutePath());
bw = Files.newBufferedWriter(outputFile.toPath(), Charset.defaultCharset(),
StandardOpenOption.CREATE);
try {
currentStoreBaseDir = currentStore.getBaseDir();
} catch (Exception e) {
LOGGER.warn("Could not get baseDir of store: {}", storeID, e);
currentStoreBaseDir = null;
}
}
String path = currentStoreBaseDir != null ? currentStore.getLocalFile(storageID).getAbsolutePath()
: storageID;
//current store initialized
String line = new MessageFormat("{0} {1}\n", Locale.ROOT).format(new Object[] { md5, path });
bw.write(line);
}
} finally {
if (bw != null) {
try {
bw.close();
} catch (IOException e1) {
LOGGER.warn("Error while closing file.", e1);
}
}
em.clear();
}
}
@Decision(HANDLE_OK)
public Permission find(Permission permission, EntityManager em) {
em.detach(permission);
return permission;
}