entityManager 如何执行自定义insert语句 ?

求助,entityManager 如何执行自定义insert语句 ?

3个回答

em.createNativeQuery("insert into user (name, password) values (?, ?)").setParameter(1, "zhangsan").setParameter(2, "zhangsan");

qq_40277452
qq_40277452 不起作用也不报错
大约一年之前 回复

entityManager.createNativeQuery(updateSql).executeUpdate();

qq_39731741
角谷 回复qq_40277452: 能啊
大约一年之前 回复
qq_40277452
qq_40277452 executeUpdate能做select操作吗
大约一年之前 回复
qq_40277452
qq_40277452 不起作用也不报错
大约一年之前 回复

entityManager.createNativeQuery(updateSql).executeUpdate();
在你的方法里调用这个原生态数据库持久化操作,如果方法里仅仅是这一句,你会发现报错提示你说这个是“一个更新/删除操作”:Executing an update/delete query,嗯,我解决这个问题的时候,翻遍了资料愣是没找到,整了一整天,快下班的时候,灵光一闪,怕不是事务的问题吧??!于是乎,在方法
的头部加了俩注解@Modifying,@Transactional,然后。。。然后就TM解决了!!!你可以定义个变量接收,如:
int result = entityManager.createNativeQuery(updateSql).executeUpdate();
如果执行成功的话,此时result=1;
百搜不得其果时,此时就得靠自己了。

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
外键约束失败,因为insert语句尚未提交(MySQL)

<div class="post-text" itemprop="text"> <p>I have a PHP script using <a href="http://en.wikipedia.org/wiki/Doctrine_%28PHP%29" rel="nofollow">Doctrine</a> 2 which does essentially the following:</p> <pre><code>$entityManager-&gt;transactional(function($em) { $foreignObject = new DoctrineEntities\ForeignTable(); $em-&gt;persist($foreignObject); $em-&gt;flush(); $aObject = new DoctrineEntities\A(); $aObject-&gt;ForeignID = $foreignObject-&gt;ID; $em-&gt;persist($aObject); $em-&gt;flush(); }); </code></pre> <p>I'm getting an integrity constraint violation:</p> <blockquote> <p><i>a foreign key constraint fails (dbName.A, CONSTRAINT A_ForeignID FOREIGN KEY (ForeignID) REFERENCES <code>ForeignTable</code> (<code>ID</code>) ON DELETE NO ACTION ON UPDATE NO ACTION)</i></p> </blockquote> <p>My guess is that the constraint is checked before the commit, and it doesn't check to see whether an insert I made that hasn't been committed yet might make the constraint pass rather than fail. But I really do want these two insert statements wrapped in the same transaction. So what can I do?</p> <p><strong>UPDATE</strong></p> <p>I moved <code>$em-&gt;persist($aObject); $em-&gt;flush();</code> out of the transaction and I'm still getting the same error. Apparently, my guess was wrong... But then I really don't know what's causing the error.</p> <hr> <p><em><strong>SQL Context</strong></em></p> <p>Table <strong>A</strong></p> <pre><code>CREATE TABLE `A` ( `ID` int(11) NOT NULL AUTO_INCREMENT, `ForeignID` int(11) NOT NULL, PRIMARY KEY (`ID`), KEY `A_ForeignID` (`ForeignID`), CONSTRAINT `A_ForeignID` FOREIGN KEY (`ForeignID`) REFERENCES `ForeignTable` (`ID`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_swedish_ci </code></pre> <p>Table <strong>ForeignTable</strong></p> <pre><code>CREATE TABLE `ForeignTable` ( `ID` int(11) NOT NULL AUTO_INCREMENT, PRIMARY KEY (`ID`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_swedish_ci </code></pre> </div>

jpa原生sql插入数据,参数如何设置?

我用的Jpa原生sql语句插入Mysql数据库,不知道插入时参数如何设置,代码如下: query=em.createNativeQuery("insert into store_buy(product_name,numbers,price,style,ower,orderdate,descs) values(product_name=:product_name,numbers=:numbers,price=:price,style=:style,ower=:ower,orderdate=:orderdate,descs=:descs)"); query.setParameter("product_name", "aaaabb"); query.setParameter("numbers", 100); query.setParameter("price", 100); query.setParameter("style", "aa"); query.setParameter("ower", "aaaa"); query.setParameter("orderdate", "aaa"); query.setParameter("descs", "aaaa"); 执行后,发现设置的参数没有设置成功成功(日志如下:Hibernate: insert into store_buy(product_name,numbers,price,style,ower,orderdate,descs) values(product_name=?,numbers=?,price=?,style=?,ower=?,orderdate=?,descs=?)),查询数据库发现结果如下图: 期间不报任何错误,但是就是参数设置不成功,product_name 和 price不知道被设置成了 0,其余都是null ,确实执行插入语句了。 哪位用过这玩意儿?给指导一下,多谢

关于事物的问题EntityManager

spring Data Jpa 框架 在service注入 @Autowired private EntityManager em; 如果使用该类操作数据库 就报事物错误: No EntityManager with actualtransaction available for current thread - cannot reliably process 'persist'call 加上@Transactional注解就好了 使用 Jpa 的dao注入操作数据库就不报错 请问这个怎么解决 不想每个service都加@Transactional

我究竟如何在Symfony2 / Doctrine中创建自定义EntityManager?

<div class="post-text" itemprop="text"> <p>New guy at Symfony/Doctrine. So kindly guide me. </p> <p>Requirement: To create a custom EntityManager which would override some of the methods like remove (instead of remove, i want to perform an update and modify a parameter like isValid in my class, so that the records are never deleted) and a find ( find a record which has a non zero isValid ) etc and use it instead of Doctrine's EntityManager.</p> <p>I started reading through this thread: <a href="https://stackoverflow.com/questions/8138962/is-there-a-way-to-specify-doctrine2-entitymanager-implementation-class-in-symfon">Is there a way to specify Doctrine2 Entitymanager implementation class in Symfony2?</a> and found the answer by user2563451 to be not so straightforward. I got lost when he talks about not to follow certain approaches (again no location of the files to be modified). </p> <p>I have looked at the EntityManager.php and it specifically tells not to use extend the EntityManager class. Rather it asks to extend the EntityManagerDecorator. On looking at the EntityManagerDecorator, there are no methods available inside it (like create, persist, etc which I found in EntityManager) Does it mean I need to create new methods for each and every single Entity Manager functionality ?</p> <p>Since there is no clear defined way to get this done, I am confused to get this thing started. Also Doctrine cookbook is of little use to me as it does not have any information to achieve this.</p> <p>So any help regarding the extending of EntityManagerDecorator or EntityManager is appreciated. </p> <p>Best if you can provide me step by step directions to achieve the same.</p> <p>Thanks !</p> <p>Edit 1: my requirement is to use my custom EntityManager instead of Doctrine's EntityManager (EM) and modify those 'remove' and 'find' methods as per my requirements. I am not sure whether I need to reuse the functionality provided by Doctrine's EM or write from scratch.</p> </div>

EntityManager在service层和dao层之间的传递

<p>  我们项目现在是在dao定义了entityManager代码如下 <br />  Service: <br />  </p> <pre name="code" class="java">@Stateless @Local ({PromptPeriodService.class}) @Remote ({PromptPeriodService.class}) public class PromptPeriodServiceImpl implements PromptPeriodService { @EJB(name="PromptPeriodDAO") private static PromptPeriodDAO promptperiodDAO; @TransactionAttribute(TransactionAttributeType.REQUIRED) public void addPromptPeriodDm(PromptPeriod promptperiodNew) throws LogicException { PromptPeriod promptperiodOld = promptperiodDAO.queryPromptPeriodById(promptperiodNew.getPpdId()); if(promptperiodOld == null) { promptperiodNew.setPpdCreateDate(new Date()); promptperiodNew.setPpdUpdateDate(new Date()); promptperiodDAO.savePromptPeriod(promptperiodNew); } else { throw new LogicException(errMsg); } } } </pre> <p><br /><br />  BaseDAO:</p> <pre name="code" class="java">@Stateless public class BaseDAO { @PersistenceContext(unitName="test") protected EntityManager em; } </pre> <p><br /><br />  DAO:</p> <pre name="code" class="java">@Stateless @Remote (PromptPeriodDmDAO.class) @Local (PromptPeriodDmDAO.class) public class PromptPeriodDAOBean extends BaseDAO implements PromptPeriodDAO { public PromptPeriodDm queryPromptPeriodById(String promptperiodId) { PromptPeriod promptperiod = em.find(PromptPeriod.class, promptperiodId); return promptperiod; } } </pre> <p><br /><br />  现在的问题是我需要在service层做lazy load,但是发现在service的时候entityManager已经关闭了session。我的想法是把entityManager移到service中,但是这样的话有没有什么比较好的方法在transaction开始的时候把这个entityManager传递到dao呢? <br />  我看spring代码的时候发现spring支持hibernate的时候就是在service的transactionManager的beginTransaction时候打开session放进ThreadLocal中,之后在HibernateDaoSupport中从ThreadLocal中取出session,这样的话可以做到session的打开和关闭是和transaction的开始和结束绑定的,而且dao中用的是同一个session。现在我用的是ejb3,不知道有没有方法实现这种做法呢? <br />  我如果在service层声明entityManager,那么entityManager会和transaction的声明周期绑定,但是如何让每一个有transaction的service比较好的自动传递这个entityManager到dao呢?我有什么办法可以拦截到ejb的transaction开始和结束呢?如果可以的话,我就可以在那个开始的时候统一把那个entityManager放到threadLocal中了。 <br />  谢谢。</p> <p> </p><br /><strong>问题补充</strong><br />各位帮帮忙吧,谢谢

动态生成update语句

我要修改一个对象的字段,但是每次修改的字段个数不确定,怎么样在只写一句update语句的情况下 动态生成update语句

EntityManager由唯一键冲突关闭

<div class="post-text" itemprop="text"> <p>My application uses the Doctrine2 EntityManager. In a loop I like to insert 5 data sets to different tables.</p> <pre><code>public function insertRate($dateObj, $rate) { $model = new TestModel(); $model -&gt;setDate($dateObj) -&gt;setRate($rate); $this-&gt;getEntityManager()-&gt;persist($model); try { $this-&gt;getEntityManager()-&gt;flush(); } catch (\Exception $e) { $currentTime = new \DateTime(); echo 'Duplicate entry &lt;br&gt;' . 'At Time ' . $currentTime-&gt;format('Y-m-d H:i') . "&lt;hr&gt;"; } } </code></pre> <p>If maybe insert 2 faild because of an duplicated entry (unique constraint) the following 3 statements will not be executed by the entityManger because the manger is closed.</p> <p>I use a workaround like this:</p> <pre><code>$currentEm = $this-&gt;em; if (!$currentEm-&gt;isOpen()) { $this-&gt;em = $currentEm-&gt;create( $currentEm-&gt;getConnection(), $currentEm-&gt;getConfiguration()); } </code></pre> <p>With this workarround, a new entityManger will be set up but the auto_increment ids are not like 1, 2, 3... but 1, 5, 10, 15...</p> <p>I dont want to check if there can be a unique constraint violation because of the additional selects.</p> <p>How can I fix this, and is this workarround ok?</p> </div>

No Persistence provider for EntityManager named急急

将jbpm6的一个demo整合到自己的scop项目中一直报错,在本地用main跑没问题,用ant打包到集成环境就有问题:不知道是什么原因,求大神帮忙: javax.persistence.PersistenceException: No Persistence provider for EntityManager named org.jbpm.domain at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:69) ~[hibernate-jpa-2.0-api-1.0.1.Final.jar:1.0.1.Final] at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:47) ~[hibernate-jpa-2.0-api-1.0.1.Final.jar:1.0.1.Final] at com.ztenv.usms.bpm.service.AbstractKieServicesBase.configureServices(AbstractKieServicesBase.java:84) ~[?:?] at com.ztenv.usms.bpm.KieServicesBase.init(KieServicesBase.java:51) ~[?:?] at com.znv.icap.dcim.module.JbpmHotDeployProtocolModule.internalStart(JbpmHotDeployProtocolModule.java:22) ~[?:?] at com.znv.module.AbstractModule.start(AbstractModule.java:42) ~[scop.system.jar:?] at com.znv.module.ModuleHotDeployer.scanAddedOrUpdatedModules(ModuleHotDeployer.java:221) [scop.system.jar:?] at com.znv.module.ModuleHotDeployer.access$100(ModuleHotDeployer.java:38) [scop.system.jar:?] at com.znv.module.ModuleHotDeployer$1.run(ModuleHotDeployer.java:87) [scop.system.jar:?]

大牛帮帮忙!JPA-EntityManager只能查询,不能增删,估计是事务的问题,但不知道怎么改了

# ApplicationContext.xml <context:property-placeholder location="classpath:config/jpa/jdbc.properties" ignore-resource-not-found="true" ignore-unresolvable="true" /> <aop:aspectj-autoproxy proxy-target-class="true" /> <context:component-scan base-package="hxhz.*"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" /> </context:component-scan> <!--配置数据源 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <property name="DriverClass" value="${jdbc.driver}" /> <property name="jdbcUrl" value="${jdbc.url}" /> <property name="user" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <property name="initialPoolSize" value="${connection_pools.initial_pool_size}" /> <property name="minPoolSize" value="${connection_pools.min_pool_size}" /> <property name="maxPoolSize" value="${connection_pools.max_pool_size}" /> <property name="maxIdleTime" value="${connection_pools.max_idle_time}" /> <property name="acquireIncrement" value="${connection_pools.acquire_increment}" /> <property name="checkoutTimeout" value="${connection_pools.checkout_timeout}" /> </bean> <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="persistenceXmlLocation" value="classpath:config/jpa/persistence.xml" /> <!--加载模型对象实例 --> <property name="persistenceUnitName" value="persistenceUnit" /> <property name="jpaVendorAdapter"> <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"> <property name="showSql" value="true" /> <property name="generateDdl" value="true" /> </bean> </property> <property name="jpaProperties"> <props> <prop key="hibernate.dialect">${hibernate.dialect}</prop> <prop key="hibernate.ejb.naming_strategy">org.hibernate.cfg.ImprovedNamingStrategy</prop> <prop key="hibernate.cache.use_second_level_cache">${hibernate.cache.use_second_level_cache}</prop> <prop key="hibernate.cache.region.factory_class">${hibernate.cache.region.factory_class}</prop> <prop key="hibernate.cache.use_query_cache">${hibernate.cache.use_query_cache}</prop> <prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop> <prop key="hibernate.generate_statistics">true</prop> <prop key="hibernate.jdbc.fetch_size">${hibernate.jdbc.fetch_size}</prop> <prop key="hibernate.jdbc.batch_size">${hibernate.jdbc.batch_size}</prop> <prop key="hibernate.show_sql">${hibernate.show_sql}</prop> <prop key="hibernate.connection.isolation">2</prop> <prop key="javax.persistence.validation.mode">none</prop> <prop key="hibernate.search.default.directory_provider">org.hibernate.search.store.FSDirectoryProvider </prop> </props> </property> </bean> <!--添加配置文件 --> <bean id="config" class="hxhz.util.common.CustomizedPropertyConfig"> <property name="location" value="classpath:sys.properties" /> </bean> <bean id="jpaTemplate" class="org.springframework.orm.jpa.JpaTemplate"> <property name="entityManagerFactory" ref="entityManagerFactory" /> </bean> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource" /> </bean> <!--事务 --> <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"> <property name="entityManagerFactory" ref="entityManagerFactory" /> </bean> <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"> </bean> <aop:config> <aop:pointcut id="businessService" expression="execution(* hxhz.*.service.*.*(..))" /> <aop:advisor advice-ref="txAdvice" pointcut-ref="businessService" /> </aop:config> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="*" propagation="SUPPORTS" read-only="true" /> <tx:method name="add*" propagation="REQUIRED" /> <tx:method name="save*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="delete*" propagation="REQUIRED" /> <tx:method name="create*" propagation="REQUIRED" /> </tx:attributes> </tx:advice> # persostence.xml <persistence-unit name="persistenceUnit" transaction-type="RESOURCE_LOCAL"> <class>hxhz.model.entry.Address</class> <class>hxhz.model.entry.Developlog</class> # DAO @Repository("testbankDaoImpl") public class TestbankDaoImpl extends BaseDaoImpl<TestBank, Long> implements TestbankDao { public boolean addTestbank(TestBank testBank) { try { entityManager.persist(testBank); return true; } catch (Exception e) { e.printStackTrace(); return false; } } # BaseDao @Repository("baseDaoImpl") public class BaseDaoImpl<T, ID extends Serializable> implements BaseDao<T, ID> { @PersistenceContext(unitName="persistenceUnit") protected EntityManager entityManager; public void setEntityManagerFactory(EntityManager entityManager) { this.entityManager = entityManager; } @Autowired private JpaTemplate jpaTemplate; @Autowired private JdbcTemplate jdbcTemplate; private Class<T> entityClass;

刚开始使用jpa,不知道继承JpaRepository和使用entitymanager该如何取舍

如题,刚刚接触spring boot+jpa,就在网上查阅资料,看到的demo大多分为两种,继承JpaRepository和使用entitymanager,但是弄了半天没弄明白这两者的区别和各自的用途,求大神帮我详细解释一下,顺带给我一个demo让我进一步学习一下。

JPA查询效率过于缓慢的问题

![![图片说明](https://img-ask.csdn.net/upload/201605/12/1463050822_814178.png)图片说明](https://img-ask.csdn.net/upload/201605/12/1463050810_37325.png) 一个最简单的JPA查询语句。hibernate4.0支持的JPA版本。在数据库执行原生SQL只要5ms在JPA entityManager里用query执行JPQL却需要400MS左右。我也是醉了。没法玩了JPA。求大神给答案

初学JPA,报错求助:No Persistence provider for EntityManager named

报错信息: Exception in thread "main" javax.persistence.PersistenceException: No Persistence provider for EntityManager named jpatest at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:56) at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:34) at test.TestQuery.main(TestQuery.java:16) 附: <?xml version="1.0" encoding="UTF-8"?> <persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"> <persistence-unit name="jpatest" transaction-type="RESOURCE_LOCAL"> <provider>org.hibernate.ejb.HibernatePersistence</provider> <properties> <!--配置数据库驱动 --> <property name="hibernate.connection.driver_class" value="oracle.jdbc.driver.OracleDriver" /> <!--配置数据库用户名 --> <property name="hibernate.connection.username" value="root" /> <!--配置数据库密码 --> <property name="hibernate.connection.password" value="root" /> <!--配置数据库url --> <property name="hibernate.connection.url" value="jdbc:oracle:thin:@192.168.10.10:1521:dbtest" /> </properties> </persistence-unit> </persistence> 主方法: public class TestQuery { public static void main(String[] args) { // TODO Auto-generated method stub EntityManagerFactory emf = Persistence.createEntityManagerFactory("jpatest"); EntityManager em = emf.createEntityManager(); //.... } } 实在不知道如何下手,求助各位大神。

ssh注解整合开发中使用EntityManager遇到的问题?

今天开发微信的项目需要查询我的小伙伴的流水,也就是我推广的小伙伴的当日收款额, 收款记录表DepositRecord中没有totalMoney(当日收款)字段,我在实体类中添加了两个字段depositDate,totalMoney分别生成get/set方法且忽略与表的映射(@Transient) 但是执行hql的时候报错 String countHql = "select MID(b.updateDate, 1, 10) depositDate ,b.account.accountName,b.account.userName,SUM(b.txAmount) totalMoney" + " from Account a,DepositRecord b where a.id = b.account.id and ( a.agent=:agent or a.regChannel=:regChannel )" + " and a.personalAuthed=:personalAuthed and b.txState=:txState group by depositDate order by depositDate desc "; 异常:===Caused by: org.hibernate.hql.ast.QuerySyntaxException: unexpected token: depositDate near line 1, column 33 [select MID(b.updateDate, 1, 10) depositDate ,b.account.accountName,b.account.userName,SUM(b.txAmount) totalMoney from com.rx.cred.mo.Account a,com.rx.cred.mo.DepositRecord b where a.id = b.account.id and ( a.agent=:agent or a.regChannel=:regChannel ) and a.personalAuthed=:personalAuthed and b.txState=:txState group by depositDate order by depositDate desc ] at org.hibernate.hql.ast.QuerySyntaxException.convert(QuerySyntaxException.java:54) at org.hibernate.hql.ast.QuerySyntaxException.convert(QuerySyntaxException.java:47) at org.hibernate.hql.ast.ErrorCounter.throwQueryException(ErrorCounter.java:82) at org.hibernate.hql.ast.QueryTranslatorImpl.parse(QueryTranslatorImpl.java:284) at org.hibernate.hql.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:182) at org.hibernate.hql.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:136) at org.hibernate.engine.query.HQLQueryPlan.<init>(HQLQueryPlan.java:101) at org.hibernate.engine.query.HQLQueryPlan.<init>(HQLQueryPlan.java:80) at org.hibernate.engine.query.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:98) at org.hibernate.impl.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:156) at org.hibernate.impl.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:135) at org.hibernate.impl.SessionImpl.createQuery(SessionImpl.java:1760) at org.hibernate.ejb.AbstractEntityManagerImpl.createQuery(AbstractEntityManagerImpl.java:277)

我可以从实体的类方法中获取EntityManager吗?

<div class="post-text" itemprop="text"> <p>Is there an easy way to get Doctrine's entity manager from within an entity's class method?</p> <pre><code>&lt;?php /** @Entity */ class MyEntity { /** @Id @GeneratedValue @Column(type="integer") */ protected $id; [...] public function someFunction() { // Is there any way to get Doctrine's EntityManager in here? } } </code></pre> </div>

jpa自定义封装查询,继承JpaRepositoryFactoryBean出错!

直接上代码,在线等求各位大神帮忙! package com.example.rui.core.japcreatelike; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.support.JpaRepositoryFactory; import org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean; import org.springframework.data.jpa.repository.support.SimpleJpaRepository; import org.springframework.data.repository.core.RepositoryInformation; import org.springframework.data.repository.core.RepositoryMetadata; import org.springframework.data.repository.core.support.RepositoryFactorySupport; import javax.persistence.EntityManager; import java.io.Serializable; /** * Created by win10 on 2017/6/16 0016. */ public class CustomRepositoryFactoryBean<T extends JpaRepository<S,ID>, S, ID extends Serializable> extends JpaRepositoryFactoryBean<T, S, ID>{ @Override protected RepositoryFactorySupport createRepositoryFactory(EntityManager entityManager) { return new CustomRepositoryFactory(entityManager); } private static class CustomRepositoryFactory extends JpaRepositoryFactory { public CustomRepositoryFactory(EntityManager entityManager) { super(entityManager); } @Override protected <T, ID extends Serializable> SimpleJpaRepository<?, ?> getTargetRepository(RepositoryInformation information, EntityManager entityManager) { return new CustomRepositoryImpl<T, ID>((Class<T>) information.getDomainType(), entityManager); } @Override protected Class<?> getRepositoryBaseClass(RepositoryMetadata metadata) { return CustomRepositoryImpl.class; } } } ![图片说明](https://img-ask.csdn.net/upload/201706/16/1497582570_884918.png)

将Doctrine的EntityManager保存在会话变量中

<div class="post-text" itemprop="text"> <p>I'm developing a web-application and I'm going to use docrine framework to manage, concurrent requests and transactional queries (like inserting or updating head and rows records).</p> <p>For web necessities I thought to split operations in different steps: First step: I have a page that allows the user for inserting a HeadTable record and after that I send the information to the server, create a Entity and store it in a EntityManager with a persist function.</p> <p>Second step: The user will edit and insert all the RowsTable records. When it's all done, like before, I send all the data to the server, create Entities and Associate them to the HeadTable record.</p> <p>The final step: When the user confirm all he has done, I trigger the flush operation of the EntityManager and commit all to DataBase in a single atomic transaction. To keep all this steps toghether I put the EntityManager in a session variable and I remove it after the flush operation.</p> <p>All seems to be fine but i would like to know if it's the correct way to resolve the problem or if there's a better way.</p> </div>

Symfony 3.4服务 - Doctrine \ ORM \ EntityManager的实例,给定布尔值

<div class="post-text" itemprop="text"> <p>I currently have an error with a service since I updated to Symfony 3.4 from 3.0. </p> <p>I have a SwitchUserListener which receives a couple of objects in its construct but it fails to receive the EntityManager even though i have it Type-Hinted. I also added a public key to my services</p> <p>I get a FatalThrowableError because the class gets instantiated with a boolean instead of an EntityManager Object.</p> <p><strong>Error Message</strong></p> <blockquote> <p>Type error: Argument 10 passed to Dbm\UserBundle\Security\SwitchUserListener::__construct() must be an instance of Doctrine\ORM\EntityManager, boolean given, called in C:\wamp64\www\Portail\var\cache\dev\ContainerWyiblvw\getSecurity_Authentication_SwitchuserListener_MainService.php on line 8</p> </blockquote> <p><strong>FatalThrowableError Line</strong></p> <blockquote> <p>SwitchUserListener-&gt;__construct(object(TokenStorage), object(EmailUserProvider), object(UserChecker), 'main', object(TraceableAccessDecisionManager), object(Logger), '_switch_user', 'ROLE_ALLOWED_TO_SWITCH', object(TraceableEventDispatcher), <strong>false</strong>, object(AuthorizationChecker)) in var\cache\dev\ContainerWyiblvw\getSecurity_Authentication_SwitchuserListener_MainService.php</p> </blockquote> <p><strong>Here is what I have right now.</strong></p> <p><strong>services.yml</strong></p> <pre><code>services: _defaults: public: true autowire: true autoconfigure: true security.authentication.switchuser_listener: class: Dbm\UserBundle\Security\SwitchUserListener arguments: - '@security.token_storage' - ~ - '@security.user_checker' - ~ - '@security.access.decision_manager' - '@logger' - '' - '' - '@event_dispatcher' - '@doctrine.orm.entity_manager' - '@security.authorization_checker' tags: - { name: monolog.logger, channel: security } </code></pre> <p><strong>SwitchUserListener.php</strong></p> <pre><code>namespace Dbm\UserBundle\Security; ... use Doctrine\ORM\EntityManager; class SwitchUserListener implements ListenerInterface { private $tokenStorage; private $provider; private $userChecker; private $providerKey; private $accessDecisionManager; private $usernameParameter; private $role; private $logger; private $dispatcher; private $em; private $authCheck; public function __construct(TokenStorageInterface $tokenStorage, UserProviderInterface $provider, UserCheckerInterface $userChecker, $providerKey, AccessDecisionManagerInterface $accessDecisionManager, LoggerInterface $logger = null, $usernameParameter = '_switch_user', $role = 'ROLE_ALLOWED_TO_SWITCH', EventDispatcherInterface $dispatcher = null, EntityManager $em, AuthorizationChecker $authCheck) { ... } </code></pre> </div>

可以动态查询多个单号的语句怎么写

sql查询语句中个,select * from 表 where 开票单号=?? 我想实现?? 这里同时可以动态查询多个单号的记录,

hibernate entityManger.merge

代码如下,现在是更新语句已经生成 但是真正去插入数据实在insertTest这个方法执行完之后才去更新(也就是说每次都是循环完3条之后才写入数据库),我想要循环一条然后立刻写入数据库 需要怎么做. public T update(Object entity) { entityManager.merge(entity); return (T) entity; } public void update(TeleInsuranceLog teleLog){ teleLog.setCreatetime(new Date()); baseDao.update(teleLog); } public void insertTest(TeleInsuranceLog teleLog){ for (int i = 0; i <3; i++) { update(teleLog); try { Thread.sleep(3000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }

在中国程序员是青春饭吗?

今年,我也32了 ,为了不给大家误导,咨询了猎头、圈内好友,以及年过35岁的几位老程序员……舍了老脸去揭人家伤疤……希望能给大家以帮助,记得帮我点赞哦。 目录: 你以为的人生 一次又一次的伤害 猎头界的真相 如何应对互联网行业的「中年危机」 一、你以为的人生 刚入行时,拿着傲人的工资,想着好好干,以为我们的人生是这样的: 等真到了那一天,你会发现,你的人生很可能是这样的: ...

程序员请照顾好自己,周末病魔差点一套带走我。

程序员在一个周末的时间,得了重病,差点当场去世,还好及时挽救回来了。

和黑客斗争的 6 天!

互联网公司工作,很难避免不和黑客们打交道,我呆过的两家互联网公司,几乎每月每天每分钟都有黑客在公司网站上扫描。有的是寻找 Sql 注入的缺口,有的是寻找线上服务器可能存在的漏洞,大部分都...

搜狗输入法也在挑战国人的智商!

故事总是一个接着一个到来...上周写完《鲁大师已经彻底沦为一款垃圾流氓软件!》这篇文章之后,鲁大师的市场工作人员就找到了我,希望把这篇文章删除掉。经过一番沟通我先把这篇文章从公号中删除了...

总结了 150 余个神奇网站,你不来瞅瞅吗?

原博客再更新,可能就没了,之后将持续更新本篇博客。

副业收入是我做程序媛的3倍,工作外的B面人生是怎样的?

提到“程序员”,多数人脑海里首先想到的大约是:为人木讷、薪水超高、工作枯燥…… 然而,当离开工作岗位,撕去层层标签,脱下“程序员”这身外套,有的人生动又有趣,马上展现出了完全不同的A/B面人生! 不论是简单的爱好,还是正经的副业,他们都干得同样出色。偶尔,还能和程序员的特质结合,产生奇妙的“化学反应”。 @Charlotte:平日素颜示人,周末美妆博主 大家都以为程序媛也个个不修边幅,但我们也许...

MySQL数据库面试题(2020最新版)

文章目录数据库基础知识为什么要使用数据库什么是SQL?什么是MySQL?数据库三大范式是什么mysql有关权限的表都有哪几个MySQL的binlog有有几种录入格式?分别有什么区别?数据类型mysql有哪些数据类型引擎MySQL存储引擎MyISAM与InnoDB区别MyISAM索引与InnoDB索引的区别?InnoDB引擎的4大特性存储引擎选择索引什么是索引?索引有哪些优缺点?索引使用场景(重点)...

如果你是老板,你会不会踢了这样的员工?

有个好朋友ZS,是技术总监,昨天问我:“有一个老下属,跟了我很多年,做事勤勤恳恳,主动性也很好。但随着公司的发展,他的进步速度,跟不上团队的步伐了,有点...

我入职阿里后,才知道原来简历这么写

私下里,有不少读者问我:“二哥,如何才能写出一份专业的技术简历呢?我总感觉自己写的简历太烂了,所以投了无数份,都石沉大海了。”说实话,我自己好多年没有写过简历了,但我认识的一个同行,他在阿里,给我说了一些他当年写简历的方法论,我感觉太牛逼了,实在是忍不住,就分享了出来,希望能够帮助到你。 01、简历的本质 作为简历的撰写者,你必须要搞清楚一点,简历的本质是什么,它就是为了来销售你的价值主张的。往深...

优雅的替换if-else语句

场景 日常开发,if-else语句写的不少吧??当逻辑分支非常多的时候,if-else套了一层又一层,虽然业务功能倒是实现了,但是看起来是真的很不优雅,尤其是对于我这种有强迫症的程序"猿",看到这么多if-else,脑袋瓜子就嗡嗡的,总想着解锁新姿势:干掉过多的if-else!!!本文将介绍三板斧手段: 优先判断条件,条件不满足的,逻辑及时中断返回; 采用策略模式+工厂模式; 结合注解,锦...

离职半年了,老东家又发 offer,回不回?

有小伙伴问松哥这个问题,他在上海某公司,在离职了几个月后,前公司的领导联系到他,希望他能够返聘回去,他很纠结要不要回去? 俗话说好马不吃回头草,但是这个小伙伴既然感到纠结了,我觉得至少说明了两个问题:1.曾经的公司还不错;2.现在的日子也不是很如意。否则应该就不会纠结了。 老实说,松哥之前也有过类似的经历,今天就来和小伙伴们聊聊回头草到底吃不吃。 首先一个基本观点,就是离职了也没必要和老东家弄的苦...

2020阿里全球数学大赛:3万名高手、4道题、2天2夜未交卷

阿里巴巴全球数学竞赛( Alibaba Global Mathematics Competition)由马云发起,由中国科学技术协会、阿里巴巴基金会、阿里巴巴达摩院共同举办。大赛不设报名门槛,全世界爱好数学的人都可参与,不论是否出身数学专业、是否投身数学研究。 2020年阿里巴巴达摩院邀请北京大学、剑桥大学、浙江大学等高校的顶尖数学教师组建了出题组。中科院院士、美国艺术与科学院院士、北京国际数学...

男生更看重女生的身材脸蛋,还是思想?

往往,我们看不进去大段大段的逻辑。深刻的哲理,往往短而精悍,一阵见血。问:产品经理挺漂亮的,有点心动,但不知道合不合得来。男生更看重女生的身材脸蛋,还是...

程序员为什么千万不要瞎努力?

本文作者用对比非常鲜明的两个开发团队的故事,讲解了敏捷开发之道 —— 如果你的团队缺乏统一标准的环境,那么即使勤劳努力,不仅会极其耗时而且成果甚微,使用...

为什么程序员做外包会被瞧不起?

二哥,有个事想询问下您的意见,您觉得应届生值得去外包吗?公司虽然挺大的,中xx,但待遇感觉挺低,马上要报到,挺纠结的。

当HR压你价,说你只值7K,你该怎么回答?

当HR压你价,说你只值7K时,你可以流畅地回答,记住,是流畅,不能犹豫。 礼貌地说:“7K是吗?了解了。嗯~其实我对贵司的面试官印象很好。只不过,现在我的手头上已经有一份11K的offer。来面试,主要也是自己对贵司挺有兴趣的,所以过来看看……”(未完) 这段话主要是陪HR互诈的同时,从公司兴趣,公司职员印象上,都给予对方正面的肯定,既能提升HR的好感度,又能让谈判气氛融洽,为后面的发挥留足空间。...

面试:第十六章:Java中级开发(16k)

HashMap底层实现原理,红黑树,B+树,B树的结构原理 Spring的AOP和IOC是什么?它们常见的使用场景有哪些?Spring事务,事务的属性,传播行为,数据库隔离级别 Spring和SpringMVC,MyBatis以及SpringBoot的注解分别有哪些?SpringMVC的工作原理,SpringBoot框架的优点,MyBatis框架的优点 SpringCould组件有哪些,他们...

面试阿里p7,被按在地上摩擦,鬼知道我经历了什么?

面试阿里p7被问到的问题(当时我只知道第一个):@Conditional是做什么的?@Conditional多个条件是什么逻辑关系?条件判断在什么时候执...

面试了一个 31 岁程序员,让我有所触动,30岁以上的程序员该何去何从?

最近面试了一个31岁8年经验的程序猿,让我有点感慨,大龄程序猿该何去何从。

大三实习生,字节跳动面经分享,已拿Offer

说实话,自己的算法,我一个不会,太难了吧

程序员垃圾简历长什么样?

已经连续五年参加大厂校招、社招的技术面试工作,简历看的不下于万份 这篇文章会用实例告诉你,什么是差的程序员简历! 疫情快要结束了,各个公司也都开始春招了,作为即将红遍大江南北的新晋UP主,那当然要为小伙伴们做点事(手动狗头)。 就在公众号里公开征简历,义务帮大家看,并一一点评。《启舰:春招在即,义务帮大家看看简历吧》 一石激起千层浪,三天收到两百多封简历。 花光了两个星期的所有空闲时...

《Oracle Java SE编程自学与面试指南》最佳学习路线图2020年最新版(进大厂必备)

正确选择比瞎努力更重要!

《Oracle Java SE编程自学与面试指南》最佳学习路线图(2020最新版)

正确选择比瞎努力更重要!

都前后端分离了,咱就别做页面跳转了!统统 JSON 交互

文章目录1. 无状态登录1.1 什么是有状态1.2 什么是无状态1.3 如何实现无状态1.4 各自优缺点2. 登录交互2.1 前后端分离的数据交互2.2 登录成功2.3 登录失败3. 未认证处理方案4. 注销登录 这是本系列的第四篇,有小伙伴找不到之前文章,松哥给大家列一个索引出来: 挖一个大坑,Spring Security 开搞! 松哥手把手带你入门 Spring Security,别再问密...

字节跳动面试官竟然问了我JDBC?

轻松等回家通知

面试官:你连SSO都不懂,就别来面试了

大厂竟然要考我SSO,卧槽。

阿里面试官让我用Zk(Zookeeper)实现分布式锁

他可能没想到,我当场手写出来了

终于,月薪过5万了!

来看几个问题想不想月薪超过5万?想不想进入公司架构组?想不想成为项目组的负责人?想不想成为spring的高手,超越99%的对手?那么本文内容是你必须要掌握的。本文主要详解bean的生命...

自从喜欢上了B站这12个UP主,我越来越觉得自己是个废柴了!

不怕告诉你,我自从喜欢上了这12个UP主,哔哩哔哩成为了我手机上最耗电的软件,几乎每天都会看,可是吧,看的越多,我就越觉得自己是个废柴,唉,老天不公啊,不信你看看…… 间接性踌躇满志,持续性混吃等死,都是因为你们……但是,自己的学习力在慢慢变强,这是不容忽视的,推荐给你们! 都说B站是个宝,可是有人不会挖啊,没事,今天咱挖好的送你一箩筐,首先啊,我在B站上最喜欢看这个家伙的视频了,为啥 ,咱撇...

代码注释如此沙雕,会玩还是你们程序员!

某站后端代码被“开源”,同时刷遍全网的,还有代码里的那些神注释。 我们这才知道,原来程序员个个都是段子手;这么多年来,我们也走过了他们的无数套路… 首先,产品经理,是永远永远吐槽不完的!网友的评论也非常扎心,说看这些代码就像在阅读程序员的日记,每一页都写满了对产品经理的恨。 然后,也要发出直击灵魂的质问:你是尊贵的付费大会员吗? 这不禁让人想起之前某音乐app的穷逼Vip,果然,穷逼在哪里都是...

立即提问
相关内容推荐