Build a Mybatis+postgresql platform from the start

Source: Internet
Author: User






Recently there is a database of projects using PostgreSQL, using the original ecological mybatis operation data, the original ecological Nothing bad, But there is a tk.mybatis tool in the country to help us do a lot of practical things, most of the way we need to process the original ecological mybatis idea it is basically a good implementation, this will share the installation PostgreSQL, configuration Tk.mybatis detailed steps and in the process may encounter Some minor problems.


To install PostgreSQL, execute the following command to install:

apt-get update && apt-get install postgresql
After the server is installed, we also need a graphical interface client pdAdmin. I installed the Windows version of postgresql, which can be found at this address. After the installation is successful, a system user, a database user, the name and password are all postgres. We can create a new user or use this account directly. Anyway, this is just a test. After the installation is complete, you may encounter remote access issues:




For remote connection problems, only local connections are allowed by default. To allow other clients to connect, we can modify its configuration file. The directory of this file is located in /etc/postgresql/9.5/main. There are two files in this directory:
1: postgresql.conf, this is related to the server, there is a listen_address address, by default only listen to the local, we can modify it.


2: pg_hba.cof, this is related to user permissions, there is a connection-related configuration, which can be configured into the gateway mode

After a successful connection, it looks like this, we can create databases, tables and other objects.

Mybatis code generator, database and model mapping, this kind of mechanical work should be handed over to the machine to complete, refer to here for details.
General mapper, the CRUD operation of a single table can be extracted as a public interface, and the general mapper provided by tk.mybatis can help us solve such problems.
mapper.xml, small enough (only contains field mapping)
<mapper namespace = "com.jim.logstashmvc.dao.generated.mapper.ProductMapper">
  <resultMap id = "BaseResultMap" type = "com.jim.logstashmvc.dao.generated.entity.Product">
    <!-
      WARNING-@mbggenerated
    ->
    <id column = "id" jdbcType = "BIGINT" property = "id" />
    <result column = "name" jdbcType = "VARCHAR" property = "name" />
  </ resultMap>
</ mapper>
mapper, simple enough (only need to inherit through the mapper interface)
public interface ProductMapper extends Mapper <Product> {
}
Plugins, there are paging plug-ins, SQL performance analysis plug-ins, etc., integration with mybatis is very easy.

How to integrate with spring?

Integration of generators, you can use maven to run the code generator
Dependent packages
<!-MyBatis->
        <dependency>
            <groupId> org.mybatis </ groupId>
            <artifactId> mybatis </ artifactId>
            <version> $ {mybatis.version} </ version>
        </ dependency>

        <!-Spring Integration->
        <dependency>
            <groupId> org.mybatis </ groupId>
            <artifactId> mybatis-spring </ artifactId>
            <version> $ {mybatis.spring.version} </ version>
        </ dependency>

        <!-MBG->
        <dependency>
            <groupId> org.mybatis.generator </ groupId>
            <artifactId> mybatis-generator-core </ artifactId>
            <version> $ {MBG.version} </ version>
            <scope> compile </ scope>
            <optional> true </ optional>
        </ dependency>

        <!-Pagination->
        <dependency>
            <groupId> com.github.pagehelper </ groupId>
            <artifactId> pagehelper </ artifactId>
            <version> $ {pagehelper.version} </ version>
        </ dependency>

        <!-General Mapper->
        <dependency>
            <groupId> tk.mybatis </ groupId>
            <artifactId> mapper </ artifactId>
            <version> $ {mapper.version} </ version>
        </ dependency>

        <!-TkMybatis will use JPA annotations->
        <dependency>
            <groupId> javax.persistence </ groupId>
            <artifactId> persistence-api </ artifactId>
            <version> 1.0 </ version>
        </ dependency>

        <dependency>
            <groupId> org.postgresql </ groupId>
            <artifactId> postgresql </ artifactId>
            <version> 9.3-1102-jdbc41 </ version>
        </ dependency>
Configure the generator plugin, specify the configuration file path, and configure dependencies: one is the database driver and the other is the general mapper
<!-MBG->
            <plugin>
                <groupId> org.mybatis.generator </ groupId>
                <artifactId> mybatis-generator-maven-plugin </ artifactId>
                <version> $ {MBG.version} </ version>
                <configuration>
                    <configurationFile> $ {basedir} /src/main/resources/generator/generatorConfig.xml </ configurationFile>
                    <overwrite> true </ overwrite>
                    <verbose> true </ verbose>
                </ configuration>
                <dependencies>
                    <dependency>
                        <groupId> org.postgresql </ groupId>
                        <artifactId> postgresql </ artifactId>
                        <version> 9.3-1102-jdbc41 </ version>
                    </ dependency>

                    <dependency>
                        <groupId> tk.mybatis </ groupId>
                        <artifactId> mapper </ artifactId>
                        <version> $ {mapper.version} </ version>
                    </ dependency>

                </ dependencies>
            </ plugin>
Generator configuration file
Configure database connection
Configure the storage path of the generated model, mapper and mapper.xml
Configure the table information to be generated
Pay attention to targetRuntime, here is MyBatis3Simple, its default option is MyBatis3. If you use a generic mapper, we can write it this way when spring scans the interface.
 <bean class = "tk.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name = "sqlSessionFactoryBeanName" value = "jimSqlSessionFactory" />
        <property name = "basePackage" value = "com.jim.logstashmvc.dao.generated.mapper" />
    </ bean>
If it is MyBatis3, the generated mapper.xml format will be much more complicated. I have encountered such a problem before: the mapper.xml generated by MyBatis3 and then incorrectly configured the MapperScannerConfigurer for the following general mapper mode, suggesting that my error is as follows, the reason can It is determined to be a configuration problem (not a duplicate ID problem in a certain mapper.xml), and the configuration of non-universal mappers will be studied later.

Caused by: java.lang.IllegalArgumentException: Mapped Statements collection already contains value for com.jim.logstashmvc.dao.generated.mapper.ProductMapper.selectByExample
at org.apache.ibatis.session.Configuration $ StrictMap.put (Configuration.java:837)
at org.apache.ibatis.session.Configuration $ StrictMap.put (Configuration.java:809)
The above error message has been found because the MyBatis3 method was used to generate the Mapper, but at the same time, the common Mapper plug-in was incorrectly added in the configuration file. It will add a Mapper <T> inheritance to the Mapper interface, and once inherited After passing this interface, the method Id contained in it exactly overlaps with the method Id generated by MyBatis3, resulting in the above error when compiling.

After using the generic Mapper, there is a disadvantage that there is no strong type method when using Example, for example, it cannot be like this:

        ProductExample example = new ProductExample ();
        ProductExample.Criteria criteria = example.createCriteria ();
        if (product.getId ()! = null) {
            criteria.andIdEqualTo (product.getId ());
        }
It can only be written this way, the field name needs to be specified in the form of a string. This method is very suitable for dynamically constructing queries, such as: dynamic conditional search for list pages

        Example example = new Example (Product.class);
        Example.Criteria criteria = example.createCriteria ();
        if (product.getId ()! = null) {
            criteria.andEqualTo ("id", product.getId ());
        }
In order to be able to build with dynamic conditions in our previous project, and want to use a strongly typed Example for simple queries, we extended the targetRuntime, so that the Mapper it generates inherits from Map <T> and generates a specific method, but only generates The specific method has been adjusted in the name, a unique occupant has been added in the middle of the name, the default query method name generated by MBG is selectByExample, here we also generate a selectByConcreteExample. There is also a cost to doing this. The generated mapper.xml no longer only contains entity mapping, and the mapper interface is no longer just an inherited approximate empty interface. How to use benevolence for specifics.

public interface ImageMapper extends PartyInterface, RowBoundsMapper <Image>, BaseMapper <Image>, ExampleMapper <Image> {
    int countByConcreteExample (ImageExample example);

    int deleteByConcreteExample (ImageExample example);

    List <Image> selectByConcreteExample (ImageExample example);

    int updateByConcreteExampleSelective (@Param ("record") Image record, @Param ("example") ImageExample example);

    int updateByConcreteExample (@Param ("record") Image record, @Param ("example") ImageExample example);
}
 

The configuration of the generator is as follows:

<generatorConfiguration>
    <properties resource = "config.properties" />
    <context id = "jim" targetRuntime = "MyBatis3Simple" defaultModelType = "flat">
        <property name = "beginningDelimiter" value = "` "/>
        <property name = "endingDelimiter" value = "` "/>
        <plugin type = "$ {mapper.plugin}">
            <property name = "mappers" value = "$ {mapper.Mapper}" />
        </ plugin>
        <jdbcConnection driverClass = "$ {jdbc.driverClass}"
                        connectionURL = "$ {jdbc.url}"
                        userId = "$ {jdbc.username}"
                        password = "$ {jdbc.password}">
        </ jdbcConnection>
        <javaModelGenerator targetPackage = "$ {targetModelPackage}"
                            targetProject = "$ {targetJavaProject}" />
        <sqlMapGenerator targetPackage = "mapper" targetProject = "$ {targetResourcesProject}" />
        <javaClientGenerator targetPackage = "$ {targetMapperPackage}"
                             targetProject = "$ {targetJavaProject}"
                             type = "XMLMAPPER">
        </ javaClientGenerator>
        <table tableName = "product" domainObjectName = "Product"> </ table>
    </ context>
</ generatorConfiguration>
Configure the maven running parameters as shown.
 

The integration of mybatis is mainly to configure connection pool information, plug-ins, mapper scanning and other information.
<bean id = "jimDataSource" class = "org.apache.commons.dbcp.BasicDataSource">
        <property name = "driverClassName" value = "$ {jdbc.driverClass}" />
        <property name = "url" value = "$ {jdbc.url}" />
        <property name = "username" value = "$ {jdbc.username}" />
        <property name = "password" value = "$ {jdbc.password}" />

        <property name = "initialSize" value = "5" />
        <property name = "minIdle" value = "10" />
        <property name = "maxWait" value = "60000" />
        <property name = "timeBetweenEvictionRunsMillis" value = "60000" />
        <property name = "minEvictableIdleTimeMillis" value = "3600000" />
        <property name = "validationQuery" value = "SELECT 1" />
        <property name = "testWhileIdle" value = "true" />
        <property name = "testOnBorrow" value = "false" />
        <property name = "testOnReturn" value = "false" />
    </ bean>

    <bean id = "jimSqlSessionFactory" class = "org.mybatis.spring.SqlSessionFactoryBean">
        <property name = "dataSource" ref = "jimDataSource" />
        <property name = "mapperLocations" value = "classpath: mapper / *. xml" />
        <property name = "typeAliasesPackage" value = "com.jim.logstashmvc.dao.generated.entity" />
        <property name = "plugins">
            <array>
                <bean class = "com.github.pagehelper.PageHelper">
                    <property name = "properties">
                        <value>
                        dialect = postgresql
                        reasonable = true
                        supportMethodsArguments = true
                        returnPageInfo = check
                        params = count = countSql
                    </ value>

                    </ property>
                </ bean>
            </ array>
        </ property>

    </ bean>

    <bean class = "tk.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name = "sqlSessionFactoryBeanName" value = "jimSqlSessionFactory" />
        <property name = "basePackage" value = "com.jim.logstashmvc.dao.generated.mapper" />
    </ bean>
Usage of general mapper:
mapper, all generated mappers inherit from Mapper <T>, by default hold all common mapper interfaces, including common CRUD operations
IService, the definition of general mapper interface, we can modify this interface according to our business
@Service
public interface IService <T> {

    T selectByKey (Object key);

    int save (T entity);

    int delete (Object key);

    int updateAll (T entity);

    int updateNotNull (T entity);

    List <T> selectByExample (Object example);

    // TODO other ...
}
BaseService, the implementation class of general mapper
public abstract class BaseService <T> implements IService <T> {

    @Autowired
    protected Mapper <T> mapper;

    public Mapper <T> getMapper () {
        return mapper;
    }

    @Override
    public T selectByKey (Object key)\

{
        return mapper.selectByPrimaryKey (key);
    }

    public int save (T entity) {
        return mapper.insert (entity);
    }

    public int delete (Object key) {
        return mapper.deleteByPrimaryKey (key);
    }

    public int updateAll (T entity) {
        return mapper.updateByPrimaryKey (entity);
    }

    public int updateNotNull (T entity) {
        return mapper.updateByPrimaryKeySelective (entity);
    }

    public List <T> selectByExample (Object example) {
        return mapper.selectByExample (example);
    }

    // TODO other ...
}
Specific service
@Service
public class ProductServiceImpl extends BaseService <Product> implements ProductService {
    @Override
    public List <Product> selectByProduct (Product product, int page, int rows) {
        Example example = new Example (Product.class);
        Example.Criteria criteria = example.createCriteria ();
        if (! StringUtils.isBlank (product.getName ())) {
            criteria.andEqualTo ("name", product.getName ());
        }
        if (product.getId ()! = null) {
            criteria.andEqualTo ("id", product.getId ());
        }
        PageHelper.startPage (page, rows);
        return selectByExample (example);

    }

}
 

 

Install postgresql and successfully connect remotely, integrate MBG to generate mapper and model, then integrate mybatis with spring, and finally achieve our goal by linking it with general mapper: complete most of the work with a small amount of code, repeat the labor and hand it to the tool carry out. But the universal mapper has its advantages and disadvantages. It needs to be balanced according to the project environment, and personally feel that the benefits outweigh the disadvantages.

 



This article cites:
1: http://www.mybatis.tk/
2: https://github.com/abel533/Mybatis-Spring

http://www.cnblogs.com/ASPNET2008/p/5657027.html

 

Build a mybatis + postgresql platform from scratch

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.