我是一位长期读者,第一次发布海报。
基本上我正在编写一个基于spring 3 showcase的网络应用程序。
随后我插入了基于this tutorial写入数据库的功能。
我测试所有ORM内容的集成测试看起来很开心但是当我将项目部署到tomcat并尝试通过网站进行数据库更新时,数据库不会更新!
配置:
appContext.xml
<!-- holding properties for database connectivity / -->
<context:property-placeholder location="classpath:jdbc.properties" />
<!-- enabling annotation driven configuration / -->
<context:annotation-config />
<context:component-scan base-package="wcpackage" />
<tx:annotation-driven transaction-manager="transactionManager" />
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="${jdbc.driverClassName}" p:url="${jdbc.url}" />
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"
p:entityManagerFactory-ref="entityManagerFactory" />
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
p:dataSource-ref="dataSource" p:jpaVendorAdapter-ref="jpaAdapter">
<property name="loadTimeWeaver">
<bean
class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver" />
</property>
<property name="persistenceUnitName" value="wctemplatePU"></property>
</bean>
<bean id="jpaAdapter"
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"
p:showSql="${jpa.showSql}" />
jdbc.properties
jpa.database=gm
jpa.showSql=true
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/gm?user=gmuser&password=gmuser
的persistence.xml
<persistence 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">
<persistence-unit name="wctemplatePU" transaction-type="RESOURCE_LOCAL">
<properties>
<property name="hibernate.hbm2ddl.auto" value="validate" />
</properties>
</persistence-unit>
应提交给db的代码
@Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class)
protected Sequence persistGame(PGNGame game) {
Sequence seq = new Sequence();
seq.setType(SequenceType.GAME);
seq.setEvent(game.getTag("Event"));
seq.setSite(game.getTag("Site"));
...
sequenceDao.persist(seq);
return seq;
}
SequenceDao基本上是
public abstract class JpaDao<K, E> implements Dao<K, E> {
protected Class<E> entityClass;
@PersistenceContext
protected EntityManager entityManager;
public JpaDao() {
ParameterizedType genericSuperclass = (ParameterizedType) getClass().getGenericSuperclass();
this.entityClass = (Class<E>) genericSuperclass.getActualTypeArguments()[1];
}
public void persist(E entity) { entityManager.persist(entity); }
public void remove(E entity) { entityManager.remove(entity); }
public E findById(K id) { return entityManager.find(entityClass, id); }
}
我没有在控制台/日志中看到任何类型的错误。我做错了什么?
当我将hibernate日志记录转换为DEBUG
时,我注意到了一件事DEBUG:org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler - Creating new EntityManager for shared EntityManager invocation
DEBUG: org.hibernate.impl.SessionImpl - opened session at timestamp: 12975078282
DEBUG: org.hibernate.event.def.AbstractSaveEventListener - delaying identity-insert due to no transaction in progress
DEBUG: org.hibernate.event.def.AbstractSaveEventListener - delaying identity-insert due to no transaction in progress
DEBUG: org.springframework.orm.jpa.EntityManagerFactoryUtils - Closing JPA EntityManager
TRACE日志
DEBUG:org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler - Creating new EntityManager for shared EntityManager invocation
DEBUG: org.hibernate.impl.SessionImpl - opened session at timestamp: 12975085724
TRACE: org.hibernate.engine.IdentifierValue - id unsaved-value: 0
TRACE: org.hibernate.event.def.AbstractSaveEventListener - transient instance of: net.samuelbergin.gm.model.Player
TRACE: org.hibernate.event.def.DefaultPersistEventListener - saving transient instance
TRACE: org.hibernate.event.def.AbstractSaveEventListener - saving [net.samuelbergin.gm.model.Player#<null>]
TRACE: org.hibernate.engine.Cascade - processing cascade ACTION_PERSIST_SKIPLAZY for: net.samuelbergin.gm.model.Player
TRACE: org.hibernate.engine.Cascade - done processing cascade ACTION_PERSIST_SKIPLAZY for: net.samuelbergin.gm.model.Player
TRACE: org.hibernate.event.def.WrapVisitor - Wrapped collection in role: net.samuelbergin.gm.model.Player.sequenceList
DEBUG: org.hibernate.event.def.AbstractSaveEventListener - delaying identity-insert due to no transaction in progress
TRACE: org.hibernate.engine.Cascade - processing cascade ACTION_PERSIST_SKIPLAZY for: net.samuelbergin.gm.model.Player
TRACE: org.hibernate.engine.Cascade - cascade ACTION_PERSIST_SKIPLAZY for collection: net.samuelbergin.gm.model.Player.sequenceList
TRACE: org.hibernate.engine.CascadingAction - cascading to persist: net.samuelbergin.gm.model.Sequence
TRACE: org.hibernate.engine.IdentifierValue - id unsaved-value: 0
TRACE: org.hibernate.event.def.AbstractSaveEventListener - transient instance of: net.samuelbergin.gm.model.Sequence
TRACE: org.hibernate.event.def.DefaultPersistEventListener - saving transient instance
TRACE: org.hibernate.event.def.AbstractSaveEventListener - saving [net.samuelbergin.gm.model.Sequence#<null>]
TRACE: org.hibernate.engine.Cascade - processing cascade ACTION_PERSIST_SKIPLAZY for: net.samuelbergin.gm.model.Sequence
TRACE: org.hibernate.engine.Cascade - done processing cascade ACTION_PERSIST_SKIPLAZY for: net.samuelbergin.gm.model.Sequence
TRACE: org.hibernate.event.def.WrapVisitor - Wrapped collection in role: net.samuelbergin.gm.model.Sequence.commentList
TRACE: org.hibernate.engine.IdentifierValue - id unsaved-value: 0
DEBUG: org.hibernate.event.def.AbstractSaveEventListener - delaying identity-insert due to no transaction in progress
TRACE: org.hibernate.engine.Cascade - processing cascade ACTION_PERSIST_SKIPLAZY for: net.samuelbergin.gm.model.Sequence
TRACE: org.hibernate.engine.Cascade - cascade ACTION_PERSIST_SKIPLAZY for collection: net.samuelbergin.gm.model.Sequence.commentList
TRACE: org.hibernate.engine.Cascade - done cascade ACTION_PERSIST_SKIPLAZY for collection: net.samuelbergin.gm.model.Sequence.commentList
TRACE: org.hibernate.engine.Cascade - done processing cascade ACTION_PERSIST_SKIPLAZY for: net.samuelbergin.gm.model.Sequence
TRACE: org.hibernate.engine.Cascade - done cascade ACTION_PERSIST_SKIPLAZY for collection: net.samuelbergin.gm.model.Player.sequenceList
TRACE: org.hibernate.engine.Cascade - done processing cascade ACTION_PERSIST_SKIPLAZY for: net.samuelbergin.gm.model.Player
DEBUG: org.springframework.orm.jpa.EntityManagerFactoryUtils - Closing JPA EntityManager
TRACE: org.hibernate.impl.SessionImpl - closing session
实体定义
@Entity
@Table(name="sequences")
public class Sequence {
@Id
@GeneratedValue
private int id;
@Enumerated(EnumType.STRING)
private SequenceType type;
private String event;
private String site;
@Temporal(TemporalType.DATE)
private Date date;
private int round;
private String result;
private String eco;
private String description;
private String moves;
@ManyToOne
private Player whitePlayer;
@ManyToOne
private Player blackPlayer;
@OneToMany(cascade={CascadeType.ALL})
@JoinTable(name="sequenceComments",
joinColumns={@JoinColumn(name="sequence_fk")},
inverseJoinColumns={@JoinColumn(name="comment_fk")})
private List<Comment> commentList = new ArrayList<Comment>();
...
控制器
@Controller
@RequestMapping("/fileupload")
public class FileUploadController {
private static Logger logger = LoggerFactory.getLogger(FileUploadController.class);
@Autowired private SequenceService sequenceService;
@RequestMapping(method=RequestMethod.POST)
public void processUpload(@RequestParam MultipartFile file, HttpServletRequest request, Model model) throws IOException {
//TODO: parse pgn
List<PGNGame> pgnGameList;
String filename = file.getOriginalFilename();
try {
pgnGameList = PGNProcessor.parse(file.getInputStream());
sequenceService.createSequences(pgnGameList);
String message = "File '" + filename + "' uploaded successfully";
model.addAttribute("message", new Message(MessageType.success, message));
} catch (PGNProcessorException ppe) {
logger.error("Failed to process "+filename, ppe);
model.addAttribute("message", new Message(MessageType.error, "Failed to process "+filename+". Reason: "+ppe.getMessage()));
}
// else whole html pg is rendered instead of just a div to update
model.addAttribute("ajaxRequest", AjaxUtils.isAjaxUploadRequest(request));
}
}
服务
public class JpaSequenceService implements SequenceService {
...
public List<Sequence> createSequences(List<PGNGame> gameList) {
List<Sequence> seqList = new ArrayList<Sequence>();
for (PGNGame game : gameList) {
Sequence seq = persistGame(game);
seqList.add(seq);
}
return seqList;
}
@Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class)
protected Sequence persistGame(PGNGame game) {
/*...as above...*/
}
答案 0 :(得分:3)
@Transactional
仅在放置在从其他对象(而不是在同一对象中)调用的公共方法时才有效。
通过在对象周围创建代理来处理事务。来自外部的呼叫被代理拦截,因此启动了一个事务。代理不会拦截同一对象内的呼叫。
所以在你的情况下:
@Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class)
public List<Sequence> createSequences(List<PGNGame> gameList) {
请注意,在事务中包装工作单元通常是一种很好的做法。即使您的代码有效,也会不必要地打开和关闭多个事务。除非你想单独坚持每场比赛。如果是这种情况,那么要么在控制器中迭代列表,要么创建一个可以保存游戏的新类。
正如Augusto所指出的,如果您使用proxy-target-class="true"
作为代理,您可以进行内部调用以启动事务。但是我不鼓励这样做,因为你变得依赖于这个配置选项,并且如果你因为其他原因在将来改变,你可能会浪费时间找到现有功能停止工作的原因。