1)建立user表以及插入数据java
CREATE TABLE `user` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `name` varchar(30) DEFAULT NULL, `birthday` datetime DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
insert user(name,birthday) values("ss","2000-12-12");
2 )mybatis相关jar引入mysql
<dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.2.8</version> </dependency> <!--mybatis spring 插件 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.2</version> </dependency>
3)工程异常类DemoException定义web
路径地址以及对应源码以下:spring
package com.demo.base.Exception; public class DemoException extends Exception{ private String errorCode; public DemoException(String message, String errorCode) { super(message); this.errorCode = errorCode; } public DemoException(String message) { super(message); } }
1)表对象model-Usersql
package com.company.data.model; import com.fasterxml.jackson.annotation.JsonFormat; import java.io.Serializable; import java.util.Date; public class User implements Serializable { private Long id; private String name; private Date birthday; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @JsonFormat(pattern = "yyyy-MM-dd") public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } }
2)mybatis接口UserDao以及UserMapper.xml文件数据库
package com.company.data.dao; import com.company.data.model.User; import org.springframework.stereotype.Repository; @Repository public interface UserDao { User qryById(Long id); }
UserMapper.xmlexpress
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > <mapper namespace="com.company.data.dao.UserDao" > <resultMap id="UserResult" type="com.company.data.model.User"> <!--property为java对象属性名,column为表的列名--> <result property="id" column="id"/> <result property="name" column="name"/> <result property="birthday" column="birthday"/> </resultMap> <sql id="commonColumns"> id, name, birthday </sql> <select id="qryById" resultMap="UserResult"> SELECT <include refid="commonColumns"/> FROM user WHERE id = #{id} </select> </mapper>
3)其余配置文件spring-mvc
mybatis-config.xmlmybatis
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> </configuration>
jdbc.propertiesmvc
validationQuery=SELECT 1 jdbc.url=jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=utf-8 jdbc.username=root jdbc.password=admin
spring-mybatis.xml
<?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:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd "> <context:property-placeholder location="classpath:jdbc.properties"/> <bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <!-- 初始化链接大小 --> <property name="initialSize" value="0" /> <!-- 链接池最大使用链接数量 --> <property name="maxActive" value="20" /> <!-- 链接池最小空闲 --> <property name="minIdle" value="0" /> <!-- 获取链接最大等待时间 --> <property name="maxWait" value="60000" /> <property name="poolPreparedStatements" value="true" /> <property name="maxPoolPreparedStatementPerConnectionSize" value="33" /> <!-- 用来检测有效sql --> <property name="validationQuery" value="${validationQuery}" /> <property name="testOnBorrow" value="false" /> <property name="testOnReturn" value="false" /> <property name="testWhileIdle" value="true" /> <!-- 配置间隔多久才进行一次检测,检测须要关闭的空闲链接,单位是毫秒 --> <property name="timeBetweenEvictionRunsMillis" value="60000" /> <!-- 配置一个链接在池中最小生存的时间,单位是毫秒 --> <property name="minEvictableIdleTimeMillis" value="25200000" /> <!-- 打开removeAbandoned功能 --> <property name="removeAbandoned" value="true" /> <!-- 1800秒,也就是30分钟 --> <property name="removeAbandonedTimeout" value="1800" /> <!-- 关闭abanded链接时输出错误日志 --> <property name="logAbandoned" value="true" /> <!-- 监控数据库 --> <property name="filters" value="mergeStat" /> </bean> <!-- myBatis文件 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- 自动扫描entity目录, 省掉Configuration.xml里的手工配置 --> <property name="configLocation" value="classpath:mybatis/mybatis-config.xml"/> <property name="mapperLocations" value="classpath:mybatis/mapping/*.xml" /> </bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.company.data.dao" /> <property name="annotationClass" value="org.springframework.stereotype.Repository"/> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> </bean> <!-- 配置事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <tx:annotation-driven transaction-manager="transactionManager" /> </beans>
web.xml中contextConfigLocation值改成:classpath*:spring*.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"> <!--字符过滤器配置--> <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <servlet> <description>spring mvc servlet</description> <servlet-name>DispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value> classpath*:spring*.xml </param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>DispatcherServlet</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> </web-app>
spring-mvc.xml
<!--spring-mvc组件默认配置+启动注解等等--> <mvc:annotation-driven/> <!--spring ioc中扫描-讲注解Controller扫入--> <!--<context:component-scan base-package="com.company.controller">--> <!--<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>--> <!--</context:component-scan>--> <context:component-scan base-package="com.company"/>
1)UserService
源码:
package com.company.service; import com.company.data.dao.UserDao; import com.company.data.model.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class UserService { @Autowired private UserDao userDao; public User qryUserById(Long id){ return userDao.qryById(id); } }
2)UserController
package com.company.controller; import com.company.data.model.User; import com.company.service.UserService; import com.demo.base.Exception.DemoException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller @RequestMapping("user") public class UserController { @Autowired private UserService userService; @RequestMapping("qryUserById") @ResponseBody public User qryUserById(Long id) throws DemoException{ if(id == null){ throw new DemoException("id为空"); } return userService.qryUserById(id); } }
3)运行结果以下:
http://localhost:8080/demo-web/user/qryUserById.do?id=1