Build a mybatis+postgresql platform from scratch
Recently, a project's database uses postgresql to operate data using original mybatis. There is nothing wrong with original mybatis. However, there is a tk.mybatis tool in China that helps us do a lot of practical things. In most cases, we need to process on original mybatis. It has basically been well implemented. This article will share the detailed steps for installing postgresql, configuring tk.mybatis, and some minor problems that may be encountered in this process.
Install postgresql, execute the following command to install: Copy the code as follows: apt-get update && apt-get install postgresql
After the server is installed, we also need a client pdAdmin with a graphical interface. I installed the Windows version of postgresql, and you can find the corresponding version at this address. After the installation is successful, a system user and a database user will be created by default. The name and password are all postgres. We can create a new user or use this account directly. Anyway, I'm just a test. After the installation is complete, you may encounter remote access problems:
Remote connection problem, 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 server-related, and there is a listen_address address, which only listens to locally by default, and we can modify it.
2: pg_hba.cof, this is related to user permissions, there is a connection-related configuration, which can be configured in gateway mode
After a successful connection, it is probably like this, we can create databases, tables and other objects.
Mybatis code generator, the mapping of database and Model, such mechanical work should be left to the machine to complete. Please refer to the details here.
General mapper, a single table CRUD operation can abstract a public interface, and the general mapper provided by tk.mybatis can help us solve this type of problem.
----mapper.xml, small enough (including only field maps)
<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 (just inherit from the mapper interface)
The code copy is as follows: public interface ProductMapper extends Mapper<Product> {}
Plugins, here are paging plugins, SQL performance analysis plugins, etc., it is very easy to integrate with mybatis.
How to integrate with spring?
Integration of generators, you can use the maven method to run the code generator.
Depend on 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>Configuration generator plug-in, specify the configuration file path, configuration dependencies: one is a database driver, and the other is a 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 connections
** Configure the storage paths of the generated model, mapper and mapper.xml
** Configure the table information to be generated
Note the targetRuntime, here is MyBatis3Simple, and its default option is MyBatis3. If we use a general mapper, we can write this when scanning the interface in spring.
Copy the code as follows: <bean> <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 this problem before: using the mapper.xml generated by MyBatis3, then incorrectly configure the MapperScannerConfigurer to the following general mapper mode, which prompts me as follows. The reason can be determined to be a configuration problem (not a duplicate id in a mapper.xml). I will study the configuration of non-generic mapper later.
Copy the 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 generator is as follows:
Copy the code as follows:<generatorConfiguration> <properties resource="config.properties"/> <context targetRuntime="MyBatis3Simple" defaultModelType="flat"> <property name="beginningDelimiter" value="`"/> <property name="endDelimiter" 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 maven running parameters as shown in the figure below.
Mybatis integration mainly configures connection pool information, plug-ins, mapper scanning and other information.
<bean id="jimDataSource"> <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="testOnBorrow" value="false"/> <property name="testOnReturn" value="false"/> </bean> <bean id="jimSqlSessionFactory"> <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> <property name="properties"> <value> dialect=postgresql reasonable=true supportMethodsArguments=true returnPageInfo=check params=count=countSql </value> </property> </bean> </array> </property> </bean> <bean> <property name="sqlSessionFactoryBeanName" value="jimSqlSessionFactory"/> <property name="basePackage" value="com.jim.logstashmvc.dao.generated.mapper"/> </bean>Usage of general mapper:
• mapper, all generated mappers are inherited from Mapper<T>, and hold all interfaces of common mapper by default, including common CRUD operations.
• IService, the definition of a general 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 Others...}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 Others...}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(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 connect it through a general mapper to achieve our goal: to complete most of the work through a small amount of code, and hand it over to the tool for repeated work. But general mapper has its advantages and disadvantages, and needs to be balanced according to the project environment. I personally feel that the benefits outweigh the disadvantages.
Cited by this article:
1. http://www.mybatis.tk/
2. https://github.com/abel533/Mybatis-Spring
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.