SpringData CrudRepository仅读取(不保存,更新或删除)

时间:2019-09-01 22:13:13

标签: java mysql hibernate spring-data-jpa

我有以下问题。我想在我的应用程序中使用带有Hibernate 5的Spring Data CrudRepository。作为数据库,我使用MySQL版本5.7.21。 我认为我配置错误,因为在运行应用程序时,我只能从数据库读取数据。当我使用任何其他CrudRepository方法时。保存() 没有反应。在Hibernate日志中,我只能看到Select语句(应该有insert语句,但似乎hibernate不会创建它)。

当我使用save(animal)方法LOG时的示例日志:

Hibernate: /* load com.entity.Animal */ select animal0_.animal_id as animal_i1_0_0_, animal0_.name as name2_0_0_, animal0_.type as type3_0_0_ from animal animal0_ where animal0_.animal_id=?

这只是SpringData CrudRepository的问题,因为当我将应用程序配置为仅使用Hibernate时,我可以使用以下方式读取和写入数据库 此方法:

public void save(Animal animal) {
          sessionFactory.getCurrentSession().save(animal);
       }

我的问题是:我在配置上做错了什么?我希望能够将我的实体保存到数据库。

我将非常感谢您的任何建议或链接。

我的配置: 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>train</groupId>
    <artifactId>train</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>train Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
            <version>2.1.3.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.4.0.Final</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.1.3.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>5.1.3.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>5.1.3.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>6.0.6</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.7</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>5.4.2.Final</version>
            <scope>runtime</scope>
        </dependency>
    </dependencies>
    <build>
        <finalName>train</finalName>
    </build>
</project>


AppConfig.java

package com.configuration;


import java.util.Properties;

import javax.sql.DataSource;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.Database;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

import com.entity.Animal;

@Configuration
@EnableWebMvc
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = "com")
@ComponentScan("com")
public class AppConfig{

    // Configuration Beans
    @Bean
    public LocalSessionFactoryBean getSessionFactory() {
        Properties hibernateProperties = new Properties();
        hibernateProperties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
        hibernateProperties.put("hibernate.show_sql", "true");
        hibernateProperties.put("hibernate.generate_statistics", false);
         hibernateProperties.put("hibernate.hbm2ddl.auto", "update");
         hibernateProperties.put("hibernate.use_sql_comments", true);

        LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
        sessionFactory.setDataSource(dataSource());
        sessionFactory.setHibernateProperties(hibernateProperties);
        sessionFactory.setAnnotatedClasses(Animal.class);
        return sessionFactory;
    }

    @Bean(name="transactionManager")
     public PlatformTransactionManager txManager(){
     JpaTransactionManager jpaTransactionManager = new JpaTransactionManager(
             entityManagerFactory(dataSource()).getObject());
     return jpaTransactionManager;
     }

    @Bean
    public DataSource dataSource() {

        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/projekt?useSSL=false");
        dataSource.setUsername("Programowanie@localhost");
        dataSource.setPassword("password");

        return dataSource;
    }


    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource) {
        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        vendorAdapter.setPrepareConnection(true);
        vendorAdapter.setGenerateDdl(true);
        vendorAdapter.setDatabase(Database.MYSQL);
        LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
        factory.setJpaVendorAdapter(vendorAdapter);
        factory.setPackagesToScan("com");
        factory.setDataSource(dataSource);
        Properties hibernateProperties = new Properties();
        hibernateProperties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
        hibernateProperties.put("hibernate.show_sql", "true");
        hibernateProperties.put("hibernate.generate_statistics", false);
         hibernateProperties.put("hibernate.hbm2ddl.auto", "update");
         hibernateProperties.put("hibernate.use_sql_comments", true);
         factory.setJpaProperties(hibernateProperties);
        return factory;
    }

}

实体:Animal.java

package com.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="animal")
public class Animal {


    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="animal_id", insertable=true)
    private Long animalId;

    @Column(name="name", insertable=true)
    private String name;

    @Column(name="type", insertable=true)
    private String type;

    public Long getAnimalId() {
        return animalId;
    }

    public void setAnimalId(Long animalId) {
        this.animalId = animalId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }
}

AnimalController.java

package com;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.entity.Animal;

@RestController
@RequestMapping("/test")
public class AnimalController {
    @Autowired private AnimalService animalService;
    public AnimalController() {

    }
    public AnimalController(AnimalService animalService) {
        this.animalService = animalService;
    }
    @GetMapping("/hello")
    public String sayHello() {
        return "Hello World!";
    }

    @GetMapping("/animal/{id}")
    public Animal getGreeting(@PathVariable("id") Long id) {
        return animalService.getAnimal(id);
    }


    @PostMapping("/animal")
    public void saveGreeting(@RequestBody Animal animal) {
        animalService.saveAnimal(animal);
    }

}

AnimalService.java

package com;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.entity.Animal;

@Service
public class AnimalService {

    @Autowired
    private AnimalRepository animalRepository;

    public Animal saveAnimal(Animal animal) {
        return animalRepository.save(animal);
    }

    public Animal getAnimal(Long id) {
        return animalRepository.findById(id).get();
    }
}

AnimalRepository.java

package com;

import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.entity.Animal;

@Repository
@Transactional
public interface AnimalRepository extends CrudRepository<Animal, Long> {

}

1 个答案:

答案 0 :(得分:0)

存储库界面上的@Transactional注释没有太大帮助。它需要到达实际调用这些方法的位置,在您的情况下为AnimalService。您可以将它们放在每个方法或类本身上。给您的控制器加上注释也可以;取决于设置,我发现它在过去与@Controller冲突,但是在这里没有检查您的代码。

但是,在某些情况下,该注释在界面上会做一些有用的事情:使用@Transactional(readOnly = true)可以更改界面中每种方法的默认选项,并将其设置为false只有真正改变某些东西的方法。但是,这是一个优化,应该在以后出现。

您还可以在存储库界面上使用@Repository。这没有其他效果。它会触发异常转换,但是无论如何Spring Data仓库都已经做到了。