我使用Hibernate 4.3.11,Springframework 4创建了maven mvc项目 我做了一个没有xml配置的项目,当我测试事务回滚时,它写入表,甚至发生异常
我不知道为什么会这样。请帮忙......
以下是我的项目a link,供下载和帮助。
这是我的配置参数和其他文件。 HibernateConfiguration.java
package rs.co.mytest.configuration;
@Configuration
@EnableTransactionManagement
@ComponentScan({ "rs.co" })
@PropertySource(value = { "classpath:application.properties" })
public class HibernateConfiguration {
@Autowired
private Environment environment;
@Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setPackagesToScan(new String[] { "rs.co" });
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
@Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName"));
dataSource.setUrl(environment.getRequiredProperty("jdbc.url"));
dataSource.setUsername(environment.getRequiredProperty("jdbc.username"));
dataSource.setPassword(environment.getRequiredProperty("jdbc.password"));
return dataSource;
}
private Properties hibernateProperties() {
Properties properties = new Properties();
properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));
properties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql"));
properties.put("hibernate.format_sql", environment.getRequiredProperty("hibernate.format_sql"));
properties.setProperty("hibernate.hbm2ddl.auto", "create-drop");
properties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
return properties;
}
@Bean
@Autowired
public HibernateTransactionManager transactionManager(SessionFactory s) {
HibernateTransactionManager txManager = new HibernateTransactionManager();
txManager.setSessionFactory(s);
return txManager;
}
}
AppInitializer.java
public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { ApplicationContextConfig.class };
}
@Override
protected Class<?>[] getServletConfigClasses() {
return null;
}
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext appContext = new AnnotationConfigWebApplicationContext();
appContext.register(ApplicationContextConfig.class);
appContext.register(HibernateConfiguration.class);
ServletRegistration.Dynamic dispatcher = servletContext.addServlet(
"SpringDispatcher", new DispatcherServlet(appContext));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
}
}
DAO Interface and Object
@Repository
public interface MyTableDao {
public MyTableModel addMyTable(MyTableModel model) throws Exception;
public void deleteMyTable(Integer id) throws Exception;
public List<MyTableBean> listMyTable();
public MyTableModel getMyTable(Integer id);
public MyTableBean findMyTable(String naziv);
}
@Repository("MyTableDao")
@Transactional
public class MyTableDaoImpl implements MyTableDao {
@Autowired
private SessionFactory sessionFactory;
private String sqlBean = " select new rs.co.wog.sifrarnik.bean.MyTableBean("
+ " t.idMyTable as idMyTable, "
+ " t.naziv as naziv "
+ " )"
;
@SuppressWarnings("unchecked")
public List<MyTableBean> listMyTable() {
List<MyTableBean> bean;
String sql = sqlBean
+ " from MyTableModel t "
+ " order by naziv ";
Query query = sessionFactory.getCurrentSession().createQuery(sql);
bean = (List<MyTableBean>) query.list();
return bean;
}
@Override
@Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public MyTableModel addMyTable(MyTableModel ulazModel) throws Exception{
MyTableModel model = null;
Session sess = sessionFactory.openSession();
Transaction tx = null;
try{
tx = sess.beginTransaction();
if (null == ulazModel.getIdgrupa_artikla()){
model = ulazModel;
sessionFactory.getCurrentSession().save(model);
//Here I made Exception, but rollback did not happend using transactional
if (model.getIdgrupa_artikla() != null)
throw new Exception("My exception");
} else {
model = getMyTable(ulazModel.getIdgrupa_artikla());
model.azurirajModel(ulazModel);
sessionFactory.getCurrentSession().saveOrUpdate(model);
}
tx.commit();
}
catch (Exception e) {
e.printStackTrace();
if (tx!=null) tx.rollback();
throw e;
}
finally {
sess.close();
}
return model;
}
@Override
@Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public void deleteMyTable(Integer idMyTable) {
sessionFactory
.getCurrentSession()
.createQuery(
"DELETE FROM MyTableModel WHERE idMyTable =:idMyTable "
)
.setInteger("idMyTable", idMyTable)
.executeUpdate();
}
@Override
@Transactional(readOnly = true, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public MyTableModel getMyTable(Integer idMyTable) {
if ((idMyTable == null ))
return null;
MyTableModel tmpMyTable = null;
String sql =
" from MyTableModel "
+ " where idMyTable = :idMyTable ";
try {
tmpMyTable = (MyTableModel) sessionFactory.getCurrentSession()
.createQuery(sql)
.setInteger("idMyTable", idMyTable)
.uniqueResult();
} catch (Exception e) {
e.printStackTrace();
}
return tmpMyTable;
}
@Override
@Transactional(readOnly = true, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public MyTableBean findMyTable(String naziv) {
if (naziv == null)
return null;
MyTableBean tmpMyTable = null;
String sql = sqlBean
+ " from MyTableModel t "
+ " where t.naziv = :naziv ";
try {
tmpMyTable = (MyTableBean) sessionFactory.getCurrentSession()
.createQuery(sql)
.setString("naziv", naziv)
.uniqueResult();
} catch (Exception e) {
e.printStackTrace();
}
return tmpMyTable;
}
}
服务界面和对象
public interface MyTableService {
public MyTableBean addMyTable(MyTableBean bean) throws Exception ;
public void deleteMyTable(Integer IdMyTable) throws Exception ;
public List<MyTableBean> listMyTable();
public MyTableBean getMyTable(Integer IdMyTable);
public MyTableBean findMyTable(String naziv);
}
@Service("MyTable")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class MyTableServiceImpl implements MyTableService{
@Autowired
private MyTableDao MyTableDao;
@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
public MyTableBean addMyTable(MyTableBean bean) throws Exception {
MyTableModel model = new MyTableModel(bean);
return new MyTableBean(MyTableDao.addMyTable(model));
}
public void deleteMyTable(Integer Iduser) throws Exception {
MyTableDao.deleteMyTable(Iduser);
}
@Override
public List<MyTableBean> listMyTable() {
return MyTableDao.listMyTable();
}
@Override
public MyTableBean getMyTable(Integer id) {
MyTableModel model = MyTableDao.getMyTable(id);
if (null == model)
return null;
return new MyTableBean(model);
}
@Override
public MyTableBean findMyTable(String username) {
return MyTableDao.findMyTable(username);
}
}
控制器
@Controller
@RequestMapping("/")
public class AppController {
@Autowired
private MyTableService MyTableService;
@Autowired
private MyTableValidator MyTableValidator;
@ModelAttribute("locale")
public Locale locale(ModelAndView model ){
Locale l = new Locale("en_US");
model.addObject("locale", l );
return l;
}
// ////////////////// ovaj init binder je vezan za metodu save
@InitBinder
public void registerDateBinder(WebDataBinder binder,
Locale locale) {
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
binder.registerCustomEditor(Date.class, new CustomDateEditor(
dateFormat, true));
DecimalFormat df =new DecimalFormat();
DecimalFormatSymbols dfs = new DecimalFormatSymbols(locale);
/****************************************************************************/
df.setGroupingUsed(true);
df.setDecimalFormatSymbols(dfs);
df.setMaximumFractionDigits(32);
df.setMaximumIntegerDigits(32);
binder.registerCustomEditor(BigDecimal.class, new CustomNumberEditor(BigDecimal.class,df, true));
}
@ExceptionHandler(IOException.class)
public ModelAndView handleIOException(IOException ex) {
ModelAndView model1 = new ModelAndView(new RedirectView("/"));//
return model1;
}
@ModelAttribute("isarchive")
public Boolean isarchive(ModelAndView model ){
Boolean isarchive = false;
model.addObject("isarchive", isarchive);
return isarchive;
}
/**
* Simply selects the home view to render by returning its name.
*/
@RequestMapping(value = {"", "/index"}, method = RequestMethod.GET, produces = "text/plain;charset=UTF-8")
public ModelAndView index(Locale locale, Principal principal,
HttpServletRequest request, HttpServletResponse response) {
MyTableBean formBean = new MyTableBean();
ModelAndView model = new ModelAndView("index","myTableBean", formBean);//
Date date = new Date();
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
String formattedDate = dateFormat.format(date);
model.addObject("serverTime", formattedDate );
model.addObject(locale);
return model;
}
@RequestMapping(value = "/deleteMyTable", method = RequestMethod.POST, produces = "text/plain;charset=UTF-8")
public @ResponseBody
String deleteMyTablea(@RequestParam Integer idMyTable) {
String rezultat = " Obrisano " + String.valueOf(idMyTable);
try {
MyTableService.deleteMyTable(idMyTable);
} catch (Exception e) {
rezultat = "Nije obrisana ";
}
return rezultat;
}
@RequestMapping(value = "saveMyTable", method = RequestMethod.POST, produces = "text/plain;charset=UTF-8")
public @ResponseBody
ModelAndView processSubmit(
@Valid MyTableBean formBean,
BindingResult result,
Locale locale) {
MyTableValidator.validate(formBean, result);
if (result.hasErrors()) {
ModelAndView model = new ModelAndView("index","myTableBean", formBean);//
model.addObject("idgrupa_artikla", formBean.getIdgrupa_artikla());
return model;//"MyTableForm";
}
ModelAndView model = new ModelAndView(new RedirectView("index"));//
try {
MyTableService.addMyTable(formBean);
} catch(Exception e){
model = new ModelAndView("Greska");//
model.addObject("locale", locale);
model.addObject("greska_knjizenja", e.toString());
e.printStackTrace();
return model;
} finally {
}
model.addObject(locale);
return model;
}
}
和pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>rs.co</groupId>
<artifactId>SpringHibernateTransactionalExample</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>SpringHibernateTransactionalExample Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<springframework.version>4.2.4.RELEASE</springframework.version>
<springsecurity.version>4.0.4.RELEASE</springsecurity.version>
<hibernate.version>4.3.11.Final</hibernate.version>
<mysql.connector.version>5.1.35</mysql.connector.version>
<apache.tiles>3.0.5</apache.tiles>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<mail.version>1.4.7</mail.version>
<com.fasterxml.jackson.core>2.5.0</com.fasterxml.jackson.core>
<org.codehaus.jackson>1.9.13</org.codehaus.jackson>
<org.aspectj-version>1.8.5</org.aspectj-version>
</properties>
<dependencies>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.beangle.webmvc</groupId>
<artifactId>beangle-webmvc-core_2.11</artifactId>
<version>0.3.0</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${org.aspectj-version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>${springsecurity.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>${springsecurity.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
<version>${springsecurity.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.1.3.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.connector.version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.1.7</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>1.7.1</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java</artifactId>
<version>2.4.0a</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.12.1.GA</version>
</dependency>
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.8.1</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>org.jfree</groupId>
<artifactId>jfreechart</artifactId>
<version>1.0.19</version>
</dependency>
<dependency>
<groupId>org.jfree</groupId>
<artifactId>jcommon</artifactId>
<version>1.0.23</version>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.7</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${com.fasterxml.jackson.core}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${com.fasterxml.jackson.core}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${com.fasterxml.jackson.core}</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>${org.codehaus.jackson}</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>${org.codehaus.jackson}</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-lgpl</artifactId>
<version>${org.codehaus.jackson}</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-lgpl</artifactId>
<version>${org.codehaus.jackson}</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.2.11</version>
</dependency>
<dependency>
<groupId>javax.xml</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.1</version>
</dependency>
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-core</artifactId>
<version>2.1.8</version>
</dependency>
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-convention-plugin</artifactId>
<version>2.1.8</version>
</dependency>
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-json-plugin</artifactId>
<version>2.1.8</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>org.apache.tiles</groupId>
<artifactId>tiles-core</artifactId>
<version>${apache.tiles}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.apache.tiles</groupId>
<artifactId>tiles-template</artifactId>
<version>${apache.tiles}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.apache.tiles</groupId>
<artifactId>tiles-jsp</artifactId>
<version>${apache.tiles}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.apache.tiles</groupId>
<artifactId>tiles-servlet</artifactId>
<version>${apache.tiles}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j</artifactId>
<version>2.6</version>
<type>pom</type>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-web</artifactId>
<version>2.6</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-taglib</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-to-slf4j</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.5.4</version>
</dependency>
<dependency>
<groupId>org.springframework.mobile</groupId>
<artifactId>spring-mobile-device</artifactId>
<version>1.0.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.integration</groupId>
<artifactId>spring-integration-core</artifactId>
<version>4.1.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.ws</groupId>
<artifactId>spring-ws-core</artifactId>
<version>2.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0.0.Final</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.6.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.3.6.Final</version>
</dependency>
<!-- kraj jpa persistance -->
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.6</version>
<configuration>
<warSourceDirectory>src/main/webapp</warSourceDirectory>
<warName>SpringHibernateTransactionalExample</warName>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</pluginManagement>
<finalName>SpringHibernateExample</finalName>
</build>
</project>
答案 0 :(得分:1)
正如我们在评论中所讨论的那样,您使用MyISAM作为桌面背后的存储引擎。请考虑使用其他东西(InnoDB首选),因为MyISAM不支持交易。
https://dev.mysql.com/doc/refman/5.6/en/myisam-storage-engine.html