Build a mybatis+postgresql platform from the beginning
Recently, there is a project database 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, in most cases we need to process the idea of the original ecological MyBatis it has been a very good implementation, this will share the installation of PostgreSQL, configure Tk.mybatis detailed steps and in this process may encounter Some of the small problems.
Install PostgreSQL, and you can install the following command:
Copy Code code as follows:
Apt-get Update && apt-get install PostgreSQL
When the server is installed, we also need a graphical interface of the client pdadmin, I installed the Windows version of the PostgreSQL, you can go to this address to find the corresponding version. After successful installation, the default will create a system user, a database user, name and password are postgres, we can create new users can also directly use this account, anyway I this is just testing. After the installation is complete, you may experience remote access problems:
Remote connectivity issues, by default only local connections are allowed, and to allow other clients to connect, we can modify its profile, which is located in/etc/postgresql/9.5/main, which has two files in the directory:
1:postgresql.conf, this is a server-related, there is a listen_address address, the default listener only local, 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, presumably this way, we can create databases, tables, and other objects.
MyBatis code generator, database and model mapping, this type of machinery work should be given to the machine to complete, detailed use of reference here.
Universal Mapper, single-table CRUD operations can be pumped out of a common interface, and Tk.mybatis provides 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 "
name" Jdbctype= "VARCHAR" property= "name"/>
</resultMap>
</mapper>
----Mapper, simple enough (only need to inherit through Mapper interface)
Copy Code code as follows:
Public interface Productmapper extends mapper<product> {}
Plug-ins, where there are paging plug-ins, SQL performance Analysis Plug-ins, etc., and mybatis integration is very easy.
How do I integrate with spring?
Builder integration, you can use the Maven method to run the code generator
Dependent packages
<!--mybatis--> <dependency> <groupId>org.mybatis</groupId> <artifactid>mybatis< ;/artifactid> <version>${mybatis.version}</version> </dependency> <!--Spring Integration--> &
Lt;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</op Tional> </dependency> <!--pagination--> <dependency> <groupid>com.github.pagehelper</gro Upid> <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 the JPA annotations--> <depend ency> <groupId>javax.persistence</groupId> <artifactId>persistence-api</artifactId> &L t;version>1.0</version> </dependency> <dependency> <groupid>org.postgresql</groupid > <artifactId>postgresql</artifactId> <version>9.3-1102-jdbc41</version> </dependen
Cy>
Configuration Builder plug-in, specifying the profile path, configuring dependencies: One is database driven, one is universal mapper
<!--mbg--> <plugin> <groupid>org.mybatis.generator</groupid&
Gt <artifactId>mybatis-generator-maven-plugin</artifactId> <version>${mbg.version}</version > <configuration> <configurationfile>${basedir}/src/main/resources/generator/generatorconfig.xml& lt;/configurationfile> <overwrite>true</overwrite> <verbose>true</verbose> </c
onfiguration> <dependencies> <dependency> <groupId>org.postgresql</groupId> <artifactId>postgresql</artifactId> <version>9.3-1102-jdbc41</version> </dependenc y> <dependency> <groupId>tk.mybatis</groupId> <artifactid>mapper</artifact id> <version>${mapper.version}</version> </dependency> </dependencies> </ Plugin>
Builder configuration file
* * Configure database connection
* * configuration generated model,mapper and Mapper.xml storage path
* * Configure the table information that needs to be generated
Notice the Targetruntime, where the mybatis3simple is used, and the default option is MYBATIS3. If you use generic mapper, we can write this when spring scans the interface.
Copy Code code as follows:
<bean> <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 is a lot more complicated, 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 my error as follows, the reason can be identified as a configuration problem (not a duplicate ID in a mapper.xml problem), followed by the next study of the generic mapper configuration.
Copy Code code as follows:
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 configuration of the builder is detailed as follows:
Copy Code code as follows:
<generatorConfiguration> <properties resource= "config.properties"/> <context 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 run parameters as shown in the following illustration.
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=" username "Valu E= "${jdbc.username}"/> <property name= "password" value= "${jdbc.password}"/> <property name= "InitialSize" "Value=" 5 "/> <property name=" Minidle "value=" a "/> <property" name= "maxwait" value= "60000"/> <prop Erty name= "Timebetweenevictionrunsmillis" value= "60000"/> <property name= "Minevictableidletimemillis" 3600000 "/> <property name=" validationquery "value=" Select 1 "/> <property name=" Testwhileidle "value=" true "/> <property name=" Testonborrow "value=" false "/> <property name=" Testonreturn "value=" false "/> </b ean> <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 </va lue> </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>
General Mapper Usage:
Mapper, all generated mapper are inherited from Mapper<t>, and the default holds generic mapper all interfaces, including CRUD common operations
IService, the definition of Universal Mapper interface, we can modify this interface according to our own 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 class
@Service public
class Productserviceimpl extends baseservice<product> implements Productservice {
@ Override public
list<product> selectbyproduct (product product, int page, int rows) {
Example Example = new E Xample (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);
}
Installing PostgreSQL and successfully remote connections, integrating MBG generation Mapper and model, and then integrating MyBatis with spring, and finally joining together through Universal Mapper, is our goal: to do most of the work with a small amount of code, Repeat the work to the tool to complete. But the general Mapper has its advantage also has its shortcoming, needs to be balanced according to the project environment, the personal feeling benefit is bigger than the disadvantage.
This article references:
1, http://www.mybatis.tk/
2, Https://github.com/abel533/Mybatis-Spring
The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.