本文整理汇总了Java中javax.persistence.EntityManager类的典型用法代码示例。如果您正苦于以下问题:Java EntityManager类的具体用法?Java EntityManager怎么用?Java EntityManager使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
EntityManager类属于javax.persistence包,在下文中一共展示了EntityManager类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: persist
import javax.persistence.EntityManager; //导入依赖的package包/类
public static ClientPipelines persist (ClientPipelines elt) {
if (elt != null) {
EntityManager em = EMFUtil.getEMFactory().createEntityManager();
EntityTransaction trans = em.getTransaction();
try {
trans.begin();
em.persist(elt);
trans.commit();
return elt;
} catch (Exception e) {
e.printStackTrace();
trans.rollback();
}
}
return null;
}
示例2: updateEntity
import javax.persistence.EntityManager; //导入依赖的package包/类
/**
* {@inheritDoc}
*/
@Override
public boolean updateEntity(long id, Order entity) {
boolean found = false;
EntityManager em = getEM();
try {
em.getTransaction().begin();
PersistenceOrder order = em.find(getEntityClass(), id);
if (order != null) {
order.setTime(entity.getTime());
order.setTotalPriceInCents(entity.getTotalPriceInCents());
order.setAddressName(entity.getAddressName());
order.setAddress1(entity.getAddress1());
order.setAddress2(entity.getAddress2());
order.setCreditCardCompany(entity.getCreditCardCompany());
order.setCreditCardNumber(entity.getCreditCardNumber());
order.setCreditCardExpiryDate(entity.getCreditCardExpiryDate());
found = true;
}
em.getTransaction().commit();
} finally {
em.close();
}
return found;
}
示例3: getTargetRepository
import javax.persistence.EntityManager; //导入依赖的package包/类
@Override
@SuppressWarnings({"unchecked", "rawtypes"})
protected SimpleJpaRepository<?, ?> getTargetRepository(
final RepositoryMetadata metadata,
final EntityManager entityManager) {
final Class<?> repositoryInterface = metadata.getRepositoryInterface();
final JpaEntityInformation<?, Serializable> entityInformation = getEntityInformation(metadata.getDomainType());
if (isQueryDslSpecificExecutor(repositoryInterface)) {
throw new IllegalArgumentException("QueryDSL interface niet toegestaan");
}
return isMaxedRepository(repositoryInterface)
? new CustomSimpleMaxedJpaRepository(entityInformation, entityManager)
: isQuerycostRepository(repositoryInterface)
? new CustomSimpleQuerycostJpaRepository(entityInformation, entityManager, maxCostsQueryPlan)
: new CustomSimpleJpaRepository(entityInformation, entityManager);
}
示例4: testHandle
import javax.persistence.EntityManager; //导入依赖的package包/类
/**
* Test of handle method, of class ZipContentParser.
*/
@Test
public void testHandle() {
System.out.println("handle");
try {
EntityManager manager = new PersistenceProvider().get();
if(!manager.getTransaction().isActive()) {
manager.getTransaction().begin();
}
manager.persist(new Modification("ZipContentParserTest.mod",31));
manager.getTransaction().commit();
IOUtils.copy(getClass().getResourceAsStream("/test.zip"), FileUtils.openOutputStream(new File(getAllowedFolder()+"/a.zip")));
List <ProcessTask> result = get().handle(manager);
Assert.assertTrue(
"result is not of correct type",
result instanceof List<?>
);
Assert.assertEquals(
"Unexpected follow-ups",
0,
result.size()
);
} catch(Exception ex) {
Assert.fail(ex.getMessage());
}
}
示例5: executeTransaction
import javax.persistence.EntityManager; //导入依赖的package包/类
@Override
public void executeTransaction(EntityManager em) {
log.info("Force Deleting Deployment Specification: " + this.ds.getName());
// load deployment spec from database to avoid lazy loading issues
this.ds = DeploymentSpecEntityMgr.findById(em, this.ds.getId());
// remove DAI(s) for this ds
for (DistributedApplianceInstance dai : this.ds.getDistributedApplianceInstances()) {
dai.getProtectedPorts().clear();
OSCEntityManager.delete(em, dai, this.txBroadcastUtil);
}
// remove the sg reference from database
if (this.ds.getVirtualSystem().getVirtualizationConnector().getVirtualizationType().isOpenstack()) {
boolean osSgCanBeDeleted = DeploymentSpecEntityMgr.findDeploymentSpecsByVirtualSystemProjectAndRegion(em,
this.ds.getVirtualSystem(), this.ds.getProjectId(), this.ds.getRegion()).size() <= 1;
if (osSgCanBeDeleted && this.ds.getOsSecurityGroupReference() != null) {
OSCEntityManager.delete(em, this.ds.getOsSecurityGroupReference(), this.txBroadcastUtil);
}
}
// delete DS from the database
OSCEntityManager.delete(em, this.ds, this.txBroadcastUtil);
}
示例6: getUser
import javax.persistence.EntityManager; //导入依赖的package包/类
public static User getUser(String username) {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("userData");
EntityManager em = emf.createEntityManager();
EntityTransaction tx = em.getTransaction();
tx.begin();
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<User> q = cb.createQuery(User.class);
Root<User> c = q.from(User.class);
q.select(c).where(cb.equal(c.get("username"), username));
TypedQuery<User> query = em.createQuery(q);
List<User> users = query.getResultList();
em.close();
LOGGER.info("found " + users.size() + " users with username " + username);
if (users.size() == 1)
return users.get(0);
else
return null;
}
示例7: exec
import javax.persistence.EntityManager; //导入依赖的package包/类
@Override
public ListResponse<JobRecordDto> exec(ListJobRequest request, EntityManager em) throws Exception {
ListResponse<JobRecordDto> response = new ListResponse<JobRecordDto>();
// Initializing Entity Manager
OSCEntityManager<JobRecord> emgr = new OSCEntityManager<JobRecord>(JobRecord.class, em, this.txBroadcastUtil);
// to do mapping
List<JobRecordDto> dtoList = new ArrayList<JobRecordDto>();
// mapping all the job objects to job dto objects
for (JobRecord j : emgr.listAll(false, "id")) {
JobRecordDto dto = new JobRecordDto();
JobEntityManager.fromEntity(j, dto);
dtoList.add(dto);
}
response.setList(dtoList);
return response;
}
示例8: cancelTask
import javax.persistence.EntityManager; //导入依赖的package包/类
private void cancelTask(EntityManager em, RouterObjectRef taskRef)
throws NotFoundException, InvalidStateException {
Task task = app.db.task.get(em, taskRef);
switch (task.getState()) {
case waiting:
assert task.getAgent() == null : "Waiting task " + task.getRef() + " has assigned agent: "
+ task.getAgent().getRef();
task.makeCanceled();
return;
case canceled:
throw new InvalidStateException("Task already canceled");
case assigned:
case completed:
default:
throw new InvalidStateException(
"Current state cannot be switched to canceled: " + task.getState());
}
}
示例9: testPersistence
import javax.persistence.EntityManager; //导入依赖的package包/类
@Test
public void testPersistence() {
// Make sure derby.log is in target
System.setProperty("derby.stream.error.file", "target/derby.log");
TaskServiceImpl taskServiceImpl = new TaskServiceImpl();
EntityManagerFactory emf = createTestEMF();
final EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
taskServiceImpl.em = em;
TaskService taskService = taskServiceImpl;
Task task = new Task();
task.setId(1);
task.setTitle("test");
taskService.addTask(task);
Task task2 = taskService.getTask(1);
Assert.assertEquals(task.getTitle(), task2.getTitle());
em.getTransaction().commit();
em.close();
}
示例10: persist
import javax.persistence.EntityManager; //导入依赖的package包/类
public static Companies persist(Companies company) {
if (company != null) {
EntityManager em = EMFUtil.getEMFactory().createEntityManager();
EntityTransaction trans = em.getTransaction();
try {
trans.begin();
em.persist(company);
trans.commit();
return company;
} catch (Exception e) {
e.printStackTrace();
trans.rollback();
return null;
} finally {
em.close();
}
}
return null;
}
示例11: listSecurityGroupsByVcIdAndMgrId
import javax.persistence.EntityManager; //导入依赖的package包/类
public static SecurityGroup listSecurityGroupsByVcIdAndMgrId(EntityManager em, Long vcId, String mgrId) {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<SecurityGroup> query = cb.createQuery(SecurityGroup.class);
Root<SecurityGroup> root = query.from(SecurityGroup.class);
query = query.select(root)
.where(cb.equal(root.join("virtualizationConnector").get("id"), vcId),
cb.equal(root.join("securityGroupInterfaces").get("mgrSecurityGroupId"), mgrId))
.orderBy(cb.asc(root.get("name")));
try {
return em.createQuery(query).getSingleResult();
} catch (NoResultException nre) {
return null;
}
}
示例12: selectSqlQuerySingleResult
import javax.persistence.EntityManager; //导入依赖的package包/类
/**
* Use this for COUNT() and similar sql queries which are guaranteed to return a result
*/
@Nonnull
@CheckReturnValue
public <T> T selectSqlQuerySingleResult(@Nonnull final String queryString,
@Nullable final Map<String, Object> parameters,
@Nonnull final Class<T> resultClass) throws DatabaseException {
final EntityManager em = this.databaseConnection.getEntityManager();
try {
final Query q = em.createNativeQuery(queryString);
if (parameters != null) {
parameters.forEach(q::setParameter);
}
em.getTransaction().begin();
final T result = resultClass.cast(q.getSingleResult());
em.getTransaction().commit();
return setSauce(result);
} catch (final PersistenceException | ClassCastException e) {
final String message = String.format("Failed to select single result plain SQL query %s with %s parameters for class %s on DB %s",
queryString, parameters != null ? parameters.size() : "null", resultClass.getName(), this.databaseConnection.getName());
throw new DatabaseException(message, e);
} finally {
em.close();
}
}
示例13: executeTransaction
import javax.persistence.EntityManager; //导入依赖的package包/类
@Override
public void executeTransaction(EntityManager em) throws Exception {
this.vmPort = em.find(VMPort.class, this.vmPort.getId());
this.dai = em.find(DistributedApplianceInstance.class, this.dai.getId());
this.securityGroupInterface = em.find(SecurityGroupInterface.class,
this.securityGroupInterface.getId());
SdnRedirectionApi controller = this.apiFactoryService.createNetworkRedirectionApi(this.dai);
try {
DefaultNetworkPort ingressPort = new DefaultNetworkPort(this.dai.getInspectionOsIngressPortId(),
this.dai.getInspectionIngressMacAddress());
DefaultNetworkPort egressPort = new DefaultNetworkPort(this.dai.getInspectionOsEgressPortId(),
this.dai.getInspectionEgressMacAddress());
//Element object in DefaultInspectionPort is not used, hence null
controller.setInspectionHookFailurePolicy(new NetworkElementImpl(this.vmPort), new DefaultInspectionPort(ingressPort, egressPort, null),
FailurePolicyType.valueOf(this.securityGroupInterface.getFailurePolicyType().name()));
} finally {
controller.close();
}
}
示例14: merge
import javax.persistence.EntityManager; //导入依赖的package包/类
/**
* @return The managed version of the provided entity (with set autogenerated values for example).
*/
@Nonnull
@CheckReturnValue
//returns a sauced entity
public <E extends SaucedEntity<I, E>, I extends Serializable> E merge(@Nonnull final E entity)
throws DatabaseException {
final EntityManager em = this.databaseConnection.getEntityManager();
try {
em.getTransaction().begin();
final E managedEntity = em.merge(entity);
em.getTransaction().commit();
return managedEntity
.setSauce(this);
} catch (final PersistenceException e) {
final String message = String.format("Failed to merge entity %s on DB %s",
entity.toString(), this.databaseConnection.getName());
throw new DatabaseException(message, e);
} finally {
em.close();
}
}
示例15: setInsertedIds
import javax.persistence.EntityManager; //导入依赖的package包/类
/**
* Set the entity id values of given <code>entity</code> instance to be returned as an {@link OperationResult}.
* @param result OperationResult in which to set the ids
* @param entityManager EntityManager
* @param set Entity bean property set
* @param entity Entity class
* @param instance Entity instance
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
private static void setInsertedIds(OperationResult.Builder result, EntityManager entityManager,
BeanPropertySet<Object> set, Class<?> entity, Object instance, boolean bringBackGeneratedIds,
PropertyBox propertyBox) {
try {
getIds(entityManager, set, entity).forEach(p -> {
Object keyValue = set.read(p, instance);
result.withInsertedKey(p, keyValue);
if (bringBackGeneratedIds && keyValue != null) {
// set in propertybox
Property property = getPropertyForPath(p, propertyBox);
if (property != null) {
propertyBox.setValue(property, keyValue);
}
}
});
} catch (Exception e) {
LOGGER.warn("Failed to obtain entity id(s) value", e);
}
}