Tags: Mobile mall project
Mybatis and Spring environment setup
Since the DAO layer and service code we wrote may be used in the foreground and background, we built the environment in the core module
Reverse engineering
First of all, what we’re going to do is brand management, and we’re going to look at the brand management of the prototype interface
The database tables involved are already defined in our PowerDesigner
Let’s look at the data for the corresponding database table
Add reverse engineering plug-ins
<build>
<finalName>zhongfucheng</finalName>
<plugins>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.2</version>
<configuration>
<verbose>true</verbose>
<overwrite>true</overwrite>
</configuration>
</plugin>
</plugins>
</build>
Copy the code
Write reverse engineering documents
<?xml version="1.0" encoding="UTF-8" ? >
<!DOCTYPE generatorConfiguration PUBLIC
"-//mybatis.org//DTD MyBatis Generator Configuration
1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"
>
<generatorConfiguration>
<! Mysql > create driver package path
<classPathEntry location="F:\传智168期JAVA\传智168期JAVA\移动商城\shoprepository\shoprepository\repository\com\oracle\ojdbc14\10.2.0.2.0\ojdbc14-10.2.0.2.0.jar" />
<! Configure where the data source and generated code are stored
<context id="context1">
<commentGenerator>
<! Uncomment -->
<property name="suppressAllComments" value="true" />
<! Generate timestamp -->
<property name="suppressDate" value="true" />
</commentGenerator>
<jdbcConnection driverClass="oracle.jdbc.OracleDriver"
connectionURL="JDBC: oracle: thin: @ 127.0.0.1:1521: ZHONGFUCHENG" userId="zhongfucheng"
password="zhong" />
<! -- The default resource pack for the generated entity class SRC -->
<javaModelGenerator targetPackage="com.rl.ecps.model" targetProject="src/main/java" />
<! SqlMap file location, default resource pack SRC -->
<sqlMapGenerator targetPackage="com.rl.ecps.sqlMap" targetProject="src/main/java" />
<! TableName: tableName schema: do not fill in -->
<table schema="" tableName="eb_brand" enableCountByExample="false"
enableUpdateByExample="false" enableDeleteByExample="false"
enableSelectByExample="false" selectByExampleQueryId="false"
>
</table>
</context>
</generatorConfiguration>
Copy the code
Generated files:
The sqlMapping file is also a resource file, so I moved it to Resources
Write the Mybatis configuration file
sqlMapConfig.xml
<configuration>
<mappers>
<mapper resource="sqlMap/EbBrandMapper.xml"/>
</mappers>
</configuration>
Copy the code
Create beans.xml file
<?xml version="1.0" encoding="UTF-8"? >
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<! -- Open comments -->
<context:component-scan base-package="com.rl.ecps"/>
<! -- Configure connection pool -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.OracleDriver"></property>
<property name="url" value="JDBC: oracle: thin: @ 127.0.0.1:1521: ZHONGFUCHENG"></property>
<property name="username" value="zhongfucheng"></property>
<property name="password" value="zhong"></property>
</bean>
<! SessionFactory - configuration - >
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="configLocation" value="classpath:sqlMapConfig.xml"></property>
</bean>
<! -- Configure transaction manager -->
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<! -- Configure transaction specific method -->
<tx:advice id="txAdive" transaction-manager="txManager">
<tx:attributes>
<tx:method name="save*" propagation="REQUIRED"/>
<tx:method name="update*" propagation="REQUIRED"/>
<tx:method name="add*" propagation="REQUIRED"/>
<tx:method name="modify*" propagation="REQUIRED"/>
<tx:method name="delete*" propagation="REQUIRED"/>
<tx:method name="remove*" propagation="REQUIRED"/>
<tx:method name="select*" read-only="true"/>
<tx:method name="get*" read-only="true"/>
</tx:attributes>
</tx:advice>
<! -- Configuration section -->
<aop:config>
<aop:advisor advice-ref="txAdive" pointcut="execution(* com.rl.ecps.service.. *. * (..) )"/>
</aop:config>
</beans>
Copy the code
Add log4j
log4j.properties
log4j.rootLogger=DEBUG, Console
#Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n
log4j.logger.java.sql.ResultSet=INFO
log4j.logger.org.apache=INFO
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
Copy the code
Dao layer
Writing Dao interfaces
interface EbBrandDao {
void saveBrand(EbBrand brand);
EbBrand getBrandById(Long brandId);
void updateBrand(EbBrand brand);
void deleteBrand(Long brandId);
List<EbBrand> selectBrand(a);
List<EbBrand> selectBrandByName(String brandName);
}
Copy the code
## Write Dao implementation ##
/** * You can get a reference to sessionFactory by extending SqlSessionDaoSupport. * /
@Repository
public class EbBrandDaoImpl extends SqlSessionDaoSupport implements EbBrandDao {
String nameSpace = "com.rl.ecps.sqlMap.EbBrandMapper.";
public void saveBrand(EbBrand brand) {
this.getSqlSession().insert(nameSpace + "insert", brand);
}
public EbBrand getBrandById(Long brandId) {
return this.getSqlSession().selectOne(nameSpace + "selectByPrimaryKey", brandId);
}
public void updateBrand(EbBrand brand) {
The difference between / * * * updateByPrimaryKeySelective and updata: * is a dynamic SQL, one is static SQL. It's better to use dynamic SQL here. Because this is an update operation */
this.getSqlSession().update(nameSpace + "updateByPrimaryKeySelective", brand);
}
public void deleteBrand(Long brandId) {
this.getSqlSession().delete(nameSpace + "deleteByPrimaryKey", brandId);
}
public List<EbBrand> selectBrand(a) {
return this.getSqlSession().selectList(nameSpace+"selectBrand");
}
public List<EbBrand> selectBrandByName(String brandName) {
return this.getSqlSession().selectList(nameSpace+"selectBrandByName", brandName); }}Copy the code
Mybatis plugin only the last two methods are not automatically generated for us, other SQL statements are automatically generated.
<select id="selectBrand" resultMap="BaseResultMap">
select * from eb_brand
</select>
<select id="selectBrandByName" resultMap="BaseResultMap" parameterType="string">
select * from eb_brand t where t.brand_name = #{brandName}
</select>
Copy the code
Write the Service
The Service interface
public interface EbBrandService {
void saveBrand(EbBrand brand);
EbBrand getBrandById(Long brandId);
void updateBrand(EbBrand brand);
void deleteBrand(Long brandId);
List<EbBrand> selectBrand(a);
List<EbBrand> selectBrandByName(String brandName);
}
Copy the code
The Service implementation
package com.rl.ecps.service.impl;
import com.rl.ecps.dao.EbBrandDao;
import com.rl.ecps.dao.impl.EbBrandDaoImpl;
import com.rl.ecps.model.EbBrand;
import com.rl.ecps.service.EbBrandService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/** * Created by ozc on 2017/8/26. */
@Service
public class EbBrandServiceImpl implements EbBrandService {
@Autowired
private EbBrandDao brandDao;
public void saveBrand(EbBrand brand) {
brandDao.saveBrand(brand);
}
public EbBrand getBrandById(Long brandId) {
return brandDao.getBrandById(brandId);
}
public void updateBrand(EbBrand brand) {
brandDao.updateBrand(brand);
}
public void deleteBrand(Long brandId) {
brandDao.deleteBrand(brandId);
}
public List<EbBrand> selectBrand(a) {
return brandDao.selectBrand();
}
public List<EbBrand> selectBrandByName(String brandName) {
returnbrandDao.selectBrandByName(brandName); }}Copy the code
# test Service#
In idea, we create a new test directory
Use the shortcut CTRL + Shift + T on our serviceImpl
Idea will automatically create directories for the methods we want to test
When inserting data, remember to rewrite the SQL statement because there is no primary key by default. Here is how we use auto growth on primary key columns
<insert id="insert" parameterType="com.rl.ecps.model.EbBrand" >
<selectKey keyProperty="brandId" order="BEFORE" resultType="long">
select seqbrandid.nextval from dual
</selectKey>
insert into EB_BRAND (BRAND_ID, BRAND_NAME, BRAND_DESC,
IMGS, WEBSITE, BRAND_SORT
)
values (#{brandId,jdbcType=DECIMAL}, #{brandName,jdbcType=VARCHAR}, #{brandDesc,jdbcType=VARCHAR},
#{imgs,jdbcType=VARCHAR}, #{website,jdbcType=VARCHAR}, #{brandSort,jdbcType=DECIMAL}
)
</insert>
Copy the code
Insert the success
# # to summarize
- Brand management is a CURD operation, configuring reverse-engineered plug-ins from Idea. Generate corresponding POJOs and mapping files
- Write DAO, Service, Controller.
If you find this article helpful, give the author a little encouragement