Mybatis+postgresql Platform

Source: Internet
Author: User
Tags generator

Mybatis+postgresql Platform

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 comes with, can go to this address to find the corresponding version. After successful installation, the default is to create a system user, a database user, name and password are postgres, we can create a new user can also directly use this account, anyway I am just testing. After the installation is complete, you may experience remote access issues:



Remote connection problem, by default only allow local connection, 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, this directory has two files:
1:postgresql.conf, this is a server-related, there is a listen_address address, the default only listens locally, we can modify it.


2:PG_HBA.COF, this is user rights related, there is a connection-related configuration, can be configured as Gateway mode

After a successful connection, it's probably like this, and we can create objects such as databases, tables, and so on.

    • MyBatis code generator, database and model mapping, this kind of mechanical work should be given to the machine to complete, detailed use reference here.
    • Universal Mapper, a single-table crud operation can be pumped like a common interface, Tk.mybatis provides a generic mapper that can help us solve such problems.
      • Mapper.xml, small enough (contains only field mappings)
<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 Mapper interface)
Public interface Productmapper extends mapper<product> {}
    • Plugins, which have pagination plugins, SQL profiling plug-ins, and so on, are easy to integrate with MyBatis.


How do I integrate with spring?

    • Builder integration, you can run the code generator in MAVEN mode
      • Dependent packages
<!--MyBatis--<dependency> <groupId>org.mybatis</groupId> <arti Factid>mybatis</artifactid> <version>${mybatis.version}</version> &LT;/DEPENDENCY&G        T <!--Spring Integration--<dependency> <groupId>org.mybatis</groupId> <art Ifactid>mybatis-spring</artifactid> <version>${mybatis.spring.version}</version> &L T;/dependency> <!--MBG-<dependency> <groupid>org.mybatis.generator</ Groupid> <artifactId>mybatis-generator-core</artifactId> <version>${mbg.version }</version> <scope>compile</scope> <optional>true</optional> &L T;/dependency> <!--paging-<dependency> <groupid>com.github.pagehelper</g    Roupid>        <artifactId>pagehelper</artifactId> <version>${pagehelper.version}</version> </dependency> <!--Universal Mapper---<dependency> <groupId>tk.mybatis< /groupid> <artifactId>mapper</artifactId> <version>${mapper.version}</versio N> </dependency> <!--Tkmybatis will use annotations to JPA--<dependency> <group Id>javax.persistence</groupid> <artifactId>persistence-api</artifactId> <ver sion>1.0</version> </dependency> <dependency> <groupid>org.postgresql& Lt;/groupid> <artifactId>postgresql</artifactId> <version>9.3-1102-jdbc41</v Ersion> </dependency>
      • Configure the generator plug-in, specify the configuration file path, configure dependencies: One is the database driver, the other is the Universal mapper
<!--mbg--> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>${mbg.version}</v Ersion> <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&                    Gt  </dependency> <dependency> <groupId>tk.mybatis</groupId>                       <artifactId>mapper</artifactId> <version>${mapper.version} </version> </dependency> </dependencies> </plugin>
    • Generator configuration file
      • Configure Database connections
      • Configuring the generated Model,mapper and mapper.xml storage paths
      • Configure the table information that needs to be generated

Note The targetruntime, which is mybatis3simple, and its default option is MYBATIS3. If we use the Universal Mapper, we can write this 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's MyBatis3, the resulting mapper.xml format can be a lot more complex, and I've had this problem before: using MYBATIS3 to generate Mapper.xml and then error The configuration of the Mapperscannerconfigurer for the following general mapper mode, prompted me the error is as follows, the reason can be identified as a configuration problem (not an ID duplication problem in a mapper.xml), followed by a further study of the non-generic mapper configuration.

caused by:java.lang.IllegalArgumentException:Mapped statements collection already contains value for Com.jim.logstashmvc.dao.generated.mapper.ProductMapper.selectByExampleat 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 use of the MYBATIS3 way to generate mapper, but also in the configuration file error in adding a generic mapper plug-in, it will add a mapper<t> on the Mapper interface inheritance, And once inherited this through the interface, it contains the method ID and MyBatis3 generated method ID exactly duplicate, resulting in a compile-time prompt above the error.

After using the Universal mapper, one drawback is that there is no strong-type method when using example, such as:

        productexample Example =new productexample ();        Productexample.criteria Criteria=example.createcriteria ();        if (product.getid () = null) {            Criteria.andidequalto (Product.getid ());        }

In this case, the field name needs to be specified as a string. This approach is ideal for dynamically constructing queries, such as: Dynamic condition search on list pages

        Example Example = new Example (product.class);        Example.criteria Criteria = Example.createcriteria ();        if (product.getid () = null) {            Criteria.andequalto ("id", Product.getid ());        }

Our previous project, in order to be able to build using dynamic conditions, and want to use a strong type of example for a simple query, we expanded the targetruntime, so that its generated mapper is inherited from map<t> and generated a concrete method, Only the concrete method generated by the name has been adjusted, in the middle of the name added a unique possessive character, the default MBG generated Query method name is Selectbyexample, here we generate a separate selectbyconcreteexample. This also has a price, the generated mapper.xml also no longer only contains entity mappings, mapper interface is no longer just inherited the approximate empty interface, how to use the beholder.

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 detailed as follows:

<generatorConfiguration> <properties resource= "config.properties"/> <context id= "Jim" Targetruntime= "Mybatis3simple" defaultmodeltype= "flat" > <property name= "beginningdelimiter" value= "'"/> <prope Rty name= "Endingdelimiter" value= "'"/> <plugin type= "${mapper.plugin}" > <property name= "Mapp ERs "value=" ${mapper. Mapper} "/> </plugin> <jdbcconnection driverclass=" ${jdbc.driverclass} "co Nnectionurl= "${jdbc.url}" userid= "${jdbc.username}" password= "${jdbc.passwor                            D} "> </jdbcConnection> <javamodelgenerator targetpackage=" ${targetmodelpackage} " targetproject= "${targetjavaproject}"/> <sqlmapgenerator targetpackage= "mapper" targetproject= "${t                            Argetresourcesproject} "/> <javaclientgenerator targetpackage=" ${targetmapperpackage} " targetproject= "${targetjavaproject}" type= "Xmlmapper" > </javaClientGenerator> <table tablename= "Product" domainobjectname= "Product" ></table> </context></generatorconfig Uration>
    • Configure the MAVEN run parameters as shown in.

    • MyBatis integration, mainly configure the 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=" Usern Ame "value=" ${jdbc.username} "/> <property name=" password "value=" ${jdbc.password} "/> <property n Ame= "InitialSize" value= "5"/> <property name= "Minidle" value= "ten"/> <property name= "MaxWait" Val Ue= "60000"/> <property name= "Timebetweenevictionrunsmillis" value= "60000"/> <property name= "MinE Victableidletimemillis "value=" 3600000 "/> <property name=" validationquery "value=" Select 1 "/> <p Roperty name= "Testwhileidle" value= "true"/> <property name= "Testonborrow" value= "false"/> <prope Rty name= "Testonreturn" value= "false"/> </bean> <bean id= "jimsqlsessionfactory" class= "Org.mybatis.sprin G.sqlsessionfactorybean "&Gt <property name= "DataSource" ref= "Jimdatasource"/> <property name= "mapperlocations" value= "Classpath:mapper /*.xml "/> <property name=" typealiasespackage "value=" com.jim.logstashmvc.dao.generated.entity "/> &L T;property name= "Plugins" > <array> <bean class= "Com.github.pagehelper.PageHelper"                    ;                        <property name= "Properties" > <value> dialect=postgresql Reasonable=true supportmethodsarguments=true Returnpageinfo=c                Heck Params=count=countsql </value> </property> </bean> </array> </property> </bean> <bean class= "Tk.myba Tis.spring.mapper.MapperScannerConfigurer "> <property name=" sqlsessionfactorybeanname "value=" JimsqlsEssionfactory "/> <property name=" basepackage "value=" Com.jim.logstashmvc.dao.generated.mapper "/> </b Ean>
    • General Mapper Usage:
      • Mapper, all generated mapper inherit from Mapper<t>, and default holds all interfaces for generic mapper, including CRUD common operations
      • IService, the definition of the Universal Mapper interface, we can modify this interface according to our own business
@Servicepublic 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, Universal Mapper implementation class
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 categories
@Servicepublic class Productserviceimpl extends baseservice<product> implements Productservice {    @Override Public    list<product> selectbyproduct (product product, int page, int rows) {        Example Example = new Example (P Roduct.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);}    }

Installing PostgreSQL and successfully connecting remotely, integrating the MBG to generate mapper and model, then integrating MyBatis with spring, and finally connecting it through generic mapper, is what we do: with a small amount of code to do most of the work, Repeat the work to the tool to complete. But the general Mapper has its merits also has its disadvantage, needs to be balanced according to the project environment, the personal feeling benefit is bigger than the disadvantage.



This article refers to:
1:http://www.mybatis.tk/
2:https://github.com/abel533/mybatis-spring

Mybatis+postgresql Platform

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.