嗨,我在Java核心学习后正在学习Spring框架。我正在制作非常简单的CRUD MVC应用程序。有一个问题@事务性注释不起作用。在那方面有经验的人能帮我吗?栈:(Java、Spring、Hibernate, Maven)。
Pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.adrianzaplata</groupId>
<artifactId>hibernate-tutorial</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>hibernate-tutorial Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<failOnMissingWebXml>false</failOnMissingWebXml>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.12.RELEASE</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.4.27.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-orm -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>5.3.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.23</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-c3p0 -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-c3p0</artifactId>
<version>5.4.27.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/jstl/jstl -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
<build>
<finalName>hibernate-tutorial</finalName>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
我配置:
package com.adrianzaplata.project.config;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import java.beans.PropertyVetoException;
import java.util.Properties;
@Configuration
@EnableWebMvc
@EnableTransactionManagement
@ComponentScan(basePackages = {"com.adrianzaplata.project"})
public class AppConfig {
@Bean
public InternalResourceViewResolver viewResolver()
{
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
@Bean(destroyMethod = "close")
public ComboPooledDataSource comboPooledDataSource() throws PropertyVetoException {
ComboPooledDataSource cpds = new ComboPooledDataSource();
cpds.setDriverClass("com.mysql.jdbc.Driver");
cpds.setJdbcUrl("jdbc:mysql://localhost:3306/hibernate?useSSL=false");
cpds.setUser("adrian");
cpds.setPassword("chomik12");
cpds.setMinPoolSize(5);
cpds.setMaxPoolSize(20);
cpds.setMaxIdleTime(30000);
return cpds;
}
//
@Bean
public LocalSessionFactoryBean beanFactory() throws PropertyVetoException {
LocalSessionFactoryBean factory = new LocalSessionFactoryBean();
factory.setDataSource(comboPooledDataSource());
factory.setPackagesToScan("com.adrianzaplata.project.entities");
Properties hibernateProperties = new Properties();
hibernateProperties.setProperty("hibernate.dialect","org.hibernate.dialect.MySQLDialect");
hibernateProperties.setProperty("hibernate.show_sql","true");
factory.setHibernateProperties(hibernateProperties);
return factory;
}
@Bean
public PlatformTransactionManager hibernateTransactionManager() throws PropertyVetoException {
HibernateTransactionManager transactionManager
= new HibernateTransactionManager();
transactionManager.setSessionFactory(beanFactory().getObject());
return transactionManager;
}
}
my init class而不是web.xml
package com.adrianzaplata.project.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
@Configuration
public class AppInit extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return null;
}
@Override
protected Class<?>[] getServletConfigClasses() {
Class[] confClasses = {AppConfig.class};
return confClasses;
}
@Override
protected String[] getServletMappings() {
String[] mappings = {"/"};
return mappings;
}
}
控制器
package com.adrianzaplata.project.controllers;
import com.adrianzaplata.project.entities.Customer;
import com.adrianzaplata.project.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
@Controller
@RequestMapping("/customer")
public class CustomerController {
@Autowired
private CustomerService customerService;
@GetMapping("/all")
public String listCustomers(Model model)
{
List<Customer> theCustomers = customerService.getAllCustomers();
model.addAttribute("customers",theCustomers);
return "customer-all";
}
@GetMapping("/showAddForm")
public String addCustomer(@ModelAttribute("CustomerDTO") Customer customerDTO)
{
return "add-customer";
}
@PostMapping("/process-add-form")
public void processCustomer(HttpServletRequest request, HttpServletResponse response, @ModelAttribute("CustomerDTO") Customer customerDTO) throws IOException {
customerService.addCustomer(customerDTO);
response.sendRedirect(request.getContextPath()+"/customer/all");
}
}
At the moment I'm able to read customers from database but method addCustomer doesn't work unless managed transcaction manually inside saveCustomer() method. I suspect that reading customers also does not work by @Transactional annotation.
服务package com.adrianzaplata.project.service;
import com.adrianzaplata.project.dao.CustomerDao;
import com.adrianzaplata.project.entities.Customer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service
public class CustomerServiceImpl implements CustomerService {
@Autowired
private CustomerDao customerDao;
@Override
@Transactional
public List<Customer> getAllCustomers()
{
return customerDao.getCustomers();
}
@Transactional
@Override
public void addCustomer(Customer customer) {
customerDao.addCustomer(customer);
}
}
刀
package com.adrianzaplata.project.dao;
import com.adrianzaplata.project.entities.Customer;
import org.hibernate.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public class CustomerDaoImpl implements CustomerDao {
@Autowired
private SessionFactory sessionFactory;
@Override
public List<Customer> getCustomers() {
Session session = sessionFactory.openSession();
try {
SQLQuery query = session.createSQLQuery("SELECT * from customer");
query.addEntity(Customer.class);
List<Customer> customers = query.list();
return customers;
} finally {
session.close();
}
}
@Override
public void addCustomer(Customer customer) {
Session session = sessionFactory.openSession();
session.save(customer);
}
}
我只是想使用@Transactional来帮助我减少我必须用于hibernate的样板代码,但是当我使用@Transactional时,dao类的逻辑不会执行。(不对数据库进行查询)。