2017-06-21 58 views
1

我一直在嘗試學習Spring的最後三個星期做一些簡單的練習,但即使閱讀至少15個不同的教程和閱讀很多StackOverflow的答案我不能使這項工作:Spring Boot CRUD + Hibernate + JSP/JSON - 不能把它放在一起

我要讓具有以下特徵的「簡單」的應用:

  • 能夠給與一些CSS JSP頁面響應和js(在外部文件中)瀏覽時/carsweb;
  • 瀏覽到/carsjson時能夠返回JSON。這個迴應必須是實體「汽車」列表;
  • 當我們撥打電話/newcar(Car作爲JSON在請求體內)時,在DB上保存一輛新車。
  • 能夠使用Hibernate(在application.properties文件中的用戶/密碼)從MySQL數據庫中檢索和保存汽車;
  • 所有這些只使用Spring註解,如果可能的話,沒有配置XML。

我能夠做幾乎所有的事情,但我不能把它放在一起。下面是我在目前的狀態:

Source Packages

SpringBootWebApplication

@SpringBootApplication 
public class SpringBootWebApplication extends SpringBootServletInitializer { 

    public static void main(String[] args) throws Exception { 
     SpringApplication.run(SpringBootWebApplication.class, args); 
    }  
} 

的AppConfig

@Configuration 
@ComponentScan(basePackages = "com.facundo") 
public class AppConfig { 

} 

HibernateConfiguration

package com.facundo.configuration; 

import java.util.Properties; 

import javax.sql.DataSource; 

import org.hibernate.SessionFactory; 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.context.annotation.Bean; 
import org.springframework.context.annotation.ComponentScan; 
import org.springframework.context.annotation.Configuration; 
import org.springframework.context.annotation.PropertySource; 
import org.springframework.core.env.Environment; 
import org.springframework.jdbc.datasource.DriverManagerDataSource; 
import org.springframework.orm.hibernate4.HibernateTransactionManager; 
import org.springframework.orm.hibernate4.LocalSessionFactoryBean; 
import org.springframework.transaction.annotation.EnableTransactionManagement; 

@Configuration 
@EnableTransactionManagement 
@ComponentScan({ "com.facundo.configuration" }) 
@PropertySource(value = { "classpath:application.properties" }) 
public class HibernateConfiguration { 
    @Autowired 
    private Environment environment; 

    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")); 
     return properties; 
    } 

    @Bean 
    public LocalSessionFactoryBean sessionFactory() { 
     LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean(); 
     sessionFactory.setDataSource(dataSource()); 
     sessionFactory.setPackagesToScan(new String[] { "com.mkyong.model" }); 
     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; 
    } 

    @Bean 
    @Autowired 
    public HibernateTransactionManager transactionManager(SessionFactory s) { 
     HibernateTransactionManager txManager = new HibernateTransactionManager(); 
     txManager.setSessionFactory(s); 
     return txManager; 
    }  
} 

WelcomeController

@Controller 
public class WelcomeController { 
    @Autowired 
    private CarService carService; 
    @RequestMapping(value = "/carsweb", method = RequestMethod.GET) 
    public String helloHtml(Model model) { 
     return "welcome2"; 
    } 

    @RequestMapping(path = "/newcar", method = RequestMethod.POST) 
    public void postCustomer(@RequestBody Car modelo) { 
     carService.save(modelo); 
    } 
} 

CarDaoImpl

@Repository 
public class CarDaoImpl implements CarDao{ 

    @Autowired 
    private SessionFactory sessionFactory; 

    @Override 
    public void save(Car modelo) { 
     sessionFactory.getCurrentSession().persist(modelo); 
    }   
} 

CarPruebaImpl

@Service("prubaService") 
@Transactional 
public class CarPruebaImpl implements CarService{ 
    @Autowired 
    private CarDao modeloDao; 

    @Override 
    public void save(Car modelo) { 
     modeloDao.save(modelo); 
    } 
} 

的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> 

    <artifactId>spring-boot-web-jsp</artifactId> 
    <packaging>war</packaging> 
    <name>Spring Boot Web JSP Example</name> 
    <description>Spring Boot Web JSP Example</description> 
    <version>1.0</version> 

    <parent> 
     <groupId>org.springframework.boot</groupId> 
     <artifactId>spring-boot-starter-parent</artifactId> 
     <version>1.5.4.RELEASE</version> 
    </parent> 

    <properties> 
     <java.version>1.8</java.version> 
    </properties> 

    <dependencies> 

     <!-- Web --> 
     <dependency> 
      <groupId>org.springframework.boot</groupId> 
      <artifactId>spring-boot-starter-web</artifactId> 
     </dependency> 

     <!-- Web with Tomcat + Embed --> 
     <dependency> 
      <groupId>org.springframework.boot</groupId> 
      <artifactId>spring-boot-starter-tomcat</artifactId> 
      <scope>provided</scope> 
     </dependency> 

     <!-- JSTL --> 
     <dependency> 
      <groupId>javax.servlet</groupId> 
      <artifactId>jstl</artifactId> 
     </dependency> 

     <!-- Need this to compile JSP --> 
     <dependency> 
      <groupId>org.apache.tomcat.embed</groupId> 
      <artifactId>tomcat-embed-jasper</artifactId> 
      <scope>provided</scope> 
     </dependency> 

     <!-- Need this to compile JSP --> 
     <dependency> 
      <groupId>org.eclipse.jdt.core.compiler</groupId> 
      <artifactId>ecj</artifactId> 
      <version>4.6.1</version> 
      <scope>provided</scope> 
     </dependency> 

     <!-- Optional, for bootstrap --> 
     <dependency> 
      <groupId>org.webjars</groupId> 
      <artifactId>bootstrap</artifactId> 
      <version>3.3.7</version> 
     </dependency> 

     <!-- Persistencia --> 
     <dependency> 
      <groupId>org.springframework</groupId> 
      <artifactId>spring-tx</artifactId> 
     </dependency> 
     <dependency> 
      <groupId>org.springframework</groupId> 
      <artifactId>spring-orm</artifactId> 
     </dependency> 

     <!-- Hibernate --> 
     <dependency> 
      <groupId>org.hibernate</groupId> 
      <artifactId>hibernate-core</artifactId> 
     </dependency> 

     <!-- MySQL --> 
     <dependency> 
      <groupId>mysql</groupId> 
      <artifactId>mysql-connector-java</artifactId> 
     </dependency> 

     <!-- Joda-Time --> 
     <dependency> 
      <groupId>joda-time</groupId> 
      <artifactId>joda-time</artifactId> 
     </dependency> 

     <!-- To map JodaTime with database type --> 
     <dependency> 
      <groupId>org.jadira.usertype</groupId> 
      <artifactId>usertype.core</artifactId> 
      <version>3.0.0.CR1</version> 
     </dependency> 

    </dependencies> 
    <build> 
     <plugins> 
      <!-- Package as an executable jar/war --> 
      <plugin> 
       <groupId>org.springframework.boot</groupId> 
       <artifactId>spring-boot-maven-plugin</artifactId> 
      </plugin> 
     </plugins> 
    </build> 
</project> 

應用。屬性:

spring.mvc.view.prefix: /WEB-INF/jsp/ 
spring.mvc.view.suffix: .jsp 

jdbc.driverClassName = com.mysql.jdbc.Driver 
jdbc.url = jdbc:mysql://localhost:3306/websystique 
jdbc.username = root 
jdbc.password = MWtqKDeS4I 
hibernate.dialect = org.hibernate.dialect.MySQLDialect 
hibernate.show_sql = false 
hibernate.format_sql = false 

所以,這是顯示當我對項目文件夾執行

mvn spring-boot:run 

錯誤:

BeanCreationException:org.springframework.beans.factory.UnsatisfiedDependencyException:創建名爲'welcomeController'的bean時出錯:Uns 通過字段'servicioPrueba'表示的未滿足的依賴關係;嵌套的異常是org.springframework.beans.factory.Unsa tisfiedDependencyException:創建名爲'carPruebaImpl'的bean時出錯:通過域名錶示的不滿意的依賴關係 d'modeloDao';嵌套的異常是org.springframework.beans.factory.UnsatisfiedDependencyException:創建名爲'carDaoImpl'的bean 錯誤:通過字段'sessionFactory'表示的不滿足的依賴關係;嵌套異常是org.spring framework.beans.factory.BeanCreationException:在類路徑中定義的名稱爲'sessionFactory'的bean出錯時出錯urce [com/facundo/configuration/HibernateConfiguration.class]:調用init方法失敗;嵌套的例外是JAV a.lang.AbstractMethodError

我想這可以簡化爲:

錯誤創建名爲 'SessionFactory的'

最後,我想說的豆我認爲問題出現在某些配置中@ComponentScan找不到我的文件或類似的東西。
確實有很多需要改進的地方,所以如果你告訴我哪些部件真的有問題,請做。
總之,先謝謝你。

+0

請嘗試以下操作:將「SpringBootWebApplication」類移到包的外部,以便位於應用程序的根包上。不需要具有'AppConfig'和'HibernateConfiguration',將它們組合成一個Configuration類,並將它與SpringBootWebApplication類一起移到包之外以駐留在根包中。在你的新的Configuartion類中,不需要添加@ @ ComponentScan,因爲@ SpringBootApplication已經包含了這個。 –

回答

0

所以,這就是我所做的。

移除整個配置包(沒有更多HibernateConfig.java和AppConfig.java)

更改的pom.xml到僅具有:

<parent> 
     <groupId>org.springframework.boot</groupId> 
     <artifactId>spring-boot-starter-parent</artifactId> 
     <version>1.5.4.RELEASE</version> 
     <relativePath/> <!-- lookup parent from repository --> 
    </parent> 

    <dependencies> 
     <dependency> 
      <groupId>org.springframework.boot</groupId> 
      <artifactId>spring-boot-starter-web</artifactId> 
     </dependency> 
     <dependency> 
      <groupId>org.springframework.boot</groupId> 
      <artifactId>spring-boot-starter-data-jpa</artifactId> 
     </dependency> 
     <dependency> 
      <groupId>mysql</groupId> 
      <artifactId>mysql-connector-java</artifactId> 
     </dependency> 

     <!-- JSTL --> 
     <dependency> 
      <groupId>javax.servlet</groupId> 
      <artifactId>jstl</artifactId> 
     </dependency> 
     <!-- Need this to compile JSP --> 
     <dependency> 
      <groupId>org.apache.tomcat.embed</groupId> 
      <artifactId>tomcat-embed-jasper</artifactId> 
      <scope>provided</scope> 
     </dependency> 
     <!-- Need this to compile JSP --> 
     <dependency> 
      <groupId>org.eclipse.jdt.core.compiler</groupId> 
      <artifactId>ecj</artifactId> 
      <version>4.6.1</version> 
      <scope>provided</scope> 
     </dependency> 

    </dependencies> 

而改變application.properties到:

spring.datasource.url=jdbc:mysql://localhost:3306/arquitectura 
spring.datasource.username=root 
spring.datasource.password=MWtqKDeS4I 
spring.datasource.tomcat.max-wait=20000 
spring.datasource.tomcat.max-active=50 
spring.datasource.tomcat.max-idle=20 
spring.datasource.tomcat.min-idle=15 

spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQLDialect 
spring.jpa.properties.hibernate.id.new_generator_mappings = false 
spring.jpa.properties.hibernate.format_sql = true 

logging.level.org.hibernate.SQL=DEBUG 
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE 

spring.mvc.view.prefix: /WEB-INF/jsp/ 
spring.mvc.view.suffix: .jsp 

這現在可以工作,因爲Springs starter-web已經是c onfigured返回默認JSP和JSON(基於方法的返回類型:字符串JSP和ResponseEntity的JSON),並起動JPS還擁有的一切使用MySQL,如果你只改變(在DAO類)

@Autowired 
private SessionFactory sessionFactory; 

... 

sessionFactory.getCurrentSession().persist(object); 

@PersistenceContext 
private EntityManager entityManager; 

... 

entityManager.persist(object); 
相關問題