web framework Spring+SpringMvc+Jpa pure annotation building

Keywords: Java Spring MySQL Hibernate Database

0.jar package depends on maven pom.xml

  <properties>
        <spring_version>4.3.25.RELEASE</spring_version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring_version}</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>

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

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>3.6.10.Final</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>6.0.6</version>
        </dependency>


        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring_version}</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>RELEASE</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

1. The configuration files that can be automatically scanned and loaded by the servlet 3.0 container are unlimited in location and have the same effect as web.xml

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
    protected Class<?>[] getRootConfigClasses() {    // Configuration files for spring containers
        return new Class[]{SpringConfig.class};
    }

    protected Class<?>[] getServletConfigClasses() {  // Configuration file for spring MVC container
        return new Class[]{MvcConfig.class};
    }

    protected String[] getServletMappings() {    // Request path taken over by DisatcjerServlet
        return new String[]{"/"};
    }
}

2. The configuration file of the spring container, which manages all objects except those managed by the spring MVC container (such as the controller), can prevent ineffective weaving of transaction facets

package com.sw946.spring_demo.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

//Turn on the annotation scanning function and set the scanning range to exclude the configuration files and Controller components of springMvc @ComponentScan(basePackages
= {"com.sw946.spring_demo"},excludeFilters = @ComponentScan.Filter({EnableWebMvc.class, Controller.class})) public class SpringConfig { }

3. The configuration file of the springmvc container only manages the custom controller, which is complementary to the spring container

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

//open springMvc Annotation scanning function
@EnableWebMvc
//Only scanned@Controller Annotated classes included in container management
@ComponentScan(basePackages = "com.sw946.spring_demo",includeFilters = @Filter(Controller.class),useDefaultFilters = false)
public class MvcConfig extends WebMvcConfigurerAdapter {
    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {  //Configure view resolver (optional)
        registry.jsp("/", ".jsp");
    }

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {  //Configure static resource processor as web container default processor
        configurer.enable();
    }
}

4. The configuration file of JPA (data persistence layer). In this example, hibernate + mysql is used. The persistence framework and data can be replaced. The configuration idea is the same.

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
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 javax.sql.DataSource;

//Affirming as spring Profile, spring If you enable annotation scanning, this class will be used as spring Part of container configuration
@Configuration
//open jpa Annotation scanning, and given the scope, jpa Will inherit JpaRepository Interface generation implementation class of interface
@EnableJpaRepositories(basePackages = "com.sw946.spring_demo.repository")
//Turn on transaction management function
@EnableTransactionManagement
public class JpaConfig {
    @Bean
    public DataSource productDB() {     //Configure data sources,According to the actual database configuration to connect
        DriverManagerDataSource ds = new DriverManagerDataSource();
        ds.setDriverClassName("com.mysql.jdbc.Driver");
        ds.setUrl("jdbc:mysql://localhost:3306/test?serverTimezone=UTC");
        ds.setUsername("admin");
        ds.setPassword("admin");
        return ds;
    }

    @Bean
    public JpaVendorAdapter jpaVendorAdapter() {    //To configure ORM Frame, here is hibernate
        HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
        adapter.setDatabase(Database.MYSQL);
        adapter.setShowSql(true);
        adapter.setGenerateDdl(false);
        adapter.setDatabasePlatform("org.hibernate.dialect.MySQLDialect");
        return adapter;
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource, JpaVendorAdapter jpaVendorAdapter){   //Configure entity manager factory
        LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
        emf.setDataSource(dataSource);
        emf.setJpaVendorAdapter(jpaVendorAdapter);
        emf.setPackagesToScan("com.sw946.spring_demo.entity");  //Given the scanning range of Entity classes, the @ Entity annotated classes will be scanned
        return emf;
    }

    @Bean
    public PlatformTransactionManager transactionManager(LocalContainerEntityManagerFactoryBean factoryBean) {
        //Configure transaction manager, dependent on entity manager (requires connection session)
        return new JpaTransactionManager(factoryBean.getObject());
    }
}

The framework configuration is completed. The following is an example:

a. controller (pay attention to the location of the package, which is established according to the configuration of the scanning range)

import com.sw946.spring_demo.repository.GradeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class HomeController {
    @Autowired
    private GradeRepository gradeRepository;

    @RequestMapping("/home")
    @ResponseBody
    public String home() {
        return gradeRepository.findLaster().toString();
    }
}

b. persistence layer (ignoring service layer due to simple example)

import com.sw946.spring_demo.entity.Grade;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;

import java.util.List;

public interface GradeRepository extends JpaRepository<Grade,String>{
    List<Grade> findByIdLessThan(String id);    //Method name query, jpa provide

    //JPql,Native sql query
    @Query(nativeQuery=true, value = "select * from grade order by id desc limit 0,1")
    Grade findLaster();
}
package com.sw946.spring_demo.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import java.util.Date;

@Entity
public class Grade {
    @Id
    private String id;
    private String name;

    @Column(name = "create_time")
    private Date createTime;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    @Override
    public String toString() {
        return "Grade{" +
                "id='" + id + '\'' +
                ", name='" + name + '\'' +
                ", createTime=" + createTime +
                '}';
    }
}

c. database table

CREATE TABLE `grade` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) DEFAULT NULL,
  `create_time` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
INSERT INTO `grade` (`id`, `name`, `create_time`) VALUES ('1', '2019', '2019-11-18 15:50:41');
INSERT INTO `grade` (`id`, `name`, `create_time`) VALUES ('4', '2020', '2019-11-18 17:32:56');

Run tomcat, visit 127.0.0.1: port number / home, you can see the json string returned by the database, and the framework is completed!

Posted by zedan_80 on Wed, 20 Nov 2019 12:34:00 -0800