Idea搭建简单springboot项目的详细教程(三)创建目录结构与基础dao、mapper.xml...

it2023-06-08  76

一、通过插件自动生成mapper.xml

1、安装better-mybatis-gener 插件

2、连接数据库

3、 自动生成基础代码

 

具体的代码示例:

Controller控制层自己写:

package com.example.demo.controller; import com.example.demo.model.User; import com.example.demo.model.UserKey; import com.example.demo.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/user") public class UserController { @Autowired private UserService userService; /** * 测试方法 * @return */ @RequestMapping(value = "/test",method = RequestMethod.GET) public String requestTest() { return "哈哈哈"; } /** * 通过主键查询用户信息 * @param userId 用户id * @param username 用户名称 * @return */ @RequestMapping(value = "/findUser",method = RequestMethod.GET) public User findUserByPrimaryKey(Integer userId, String username) { UserKey userKey = new UserKey(); userKey.setUserId(userId); userKey.setUsername(username); return userService.findUserByPrimaryKey(userKey); } }

Service层

1、接口

package com.example.demo.service; import com.example.demo.model.User; import com.example.demo.model.UserKey; public interface UserService { /** * 通过用户主键查询用户信息 * @param userKey * @return */ User findUserByPrimaryKey(UserKey userKey); }

2、接口实现

package com.example.demo.service.impl; import com.example.demo.mapper.UserMapper; import com.example.demo.model.User; import com.example.demo.model.UserKey; import com.example.demo.service.UserService; import org.springframework.stereotype.Service; import javax.annotation.Resource; @Service public class UserServiceImpl implements UserService { @Resource private UserMapper userMapper; /** * 通过用户主键查询用户信息 * @param userKey * @return */ @Override public User findUserByPrimaryKey(UserKey userKey) { return userMapper.selectByPrimaryKey(userKey); } }

Dao/Mapper层

package com.example.demo.mapper; import com.example.demo.model.User; import com.example.demo.model.UserExample; import com.example.demo.model.UserKey; import java.util.List; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; @Mapper public interface UserMapper { long countByExample(UserExample example); int deleteByExample(UserExample example); int deleteByPrimaryKey(UserKey key); int insert(User record); int insertSelective(User record); List<User> selectByExample(UserExample example); User selectByPrimaryKey(UserKey key); int updateByExampleSelective(@Param("record") User record, @Param("example") UserExample example); int updateByExample(@Param("record") User record, @Param("example") UserExample example); int updateByPrimaryKeySelective(User record); int updateByPrimaryKey(User record); }

Mapper.xml文件

<?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.example.demo.mapper.UserMapper"> <resultMap id="BaseResultMap" type="com.example.demo.model.User"> <id column="user_id" jdbcType="INTEGER" property="userId" /> <id column="username" jdbcType="VARCHAR" property="username" /> <result column="name" jdbcType="VARCHAR" property="name" /> <result column="password" jdbcType="VARCHAR" property="password" /> <result column="createtime" jdbcType="TIMESTAMP" property="createtime" /> <result column="creator" jdbcType="INTEGER" property="creator" /> <result column="role" jdbcType="VARCHAR" property="role" /> </resultMap> <sql id="Example_Where_Clause"> <where> <foreach collection="oredCriteria" item="criteria" separator="or"> <if test="criteria.valid"> <trim prefix="(" prefixOverrides="and" suffix=")"> <foreach collection="criteria.criteria" item="criterion"> <choose> <when test="criterion.noValue"> and ${criterion.condition} </when> <when test="criterion.singleValue"> and ${criterion.condition} #{criterion.value} </when> <when test="criterion.betweenValue"> and ${criterion.condition} #{criterion.value} and #{criterion.secondValue} </when> <when test="criterion.listValue"> and ${criterion.condition} <foreach close=")" collection="criterion.value" item="listItem" open="(" separator=","> #{listItem} </foreach> </when> </choose> </foreach> </trim> </if> </foreach> </where> </sql> <sql id="Update_By_Example_Where_Clause"> <where> <foreach collection="example.oredCriteria" item="criteria" separator="or"> <if test="criteria.valid"> <trim prefix="(" prefixOverrides="and" suffix=")"> <foreach collection="criteria.criteria" item="criterion"> <choose> <when test="criterion.noValue"> and ${criterion.condition} </when> <when test="criterion.singleValue"> and ${criterion.condition} #{criterion.value} </when> <when test="criterion.betweenValue"> and ${criterion.condition} #{criterion.value} and #{criterion.secondValue} </when> <when test="criterion.listValue"> and ${criterion.condition} <foreach close=")" collection="criterion.value" item="listItem" open="(" separator=","> #{listItem} </foreach> </when> </choose> </foreach> </trim> </if> </foreach> </where> </sql> <sql id="Base_Column_List"> user_id, username, `name`, `password`, createtime, creator, `role` </sql> <select id="selectByExample" parameterType="com.example.demo.model.UserExample" resultMap="BaseResultMap"> select <if test="distinct"> distinct </if> <include refid="Base_Column_List" /> from user <if test="_parameter != null"> <include refid="Example_Where_Clause" /> </if> <if test="orderByClause != null"> order by ${orderByClause} </if> <if test="limit != null"> <if test="offset != null"> limit ${offset}, ${limit} </if> <if test="offset == null"> limit ${limit} </if> </if> </select> <select id="selectByPrimaryKey" parameterType="com.example.demo.model.UserKey" resultMap="BaseResultMap"> select <include refid="Base_Column_List" /> from user where user_id = #{userId,jdbcType=INTEGER} and username = #{username,jdbcType=VARCHAR} </select> <delete id="deleteByPrimaryKey" parameterType="com.example.demo.model.UserKey"> delete from user where user_id = #{userId,jdbcType=INTEGER} and username = #{username,jdbcType=VARCHAR} </delete> <delete id="deleteByExample" parameterType="com.example.demo.model.UserExample"> delete from user <if test="_parameter != null"> <include refid="Example_Where_Clause" /> </if> </delete> <insert id="insert" keyColumn="user_id" keyProperty="userId" parameterType="com.example.demo.model.User" useGeneratedKeys="true"> insert into user (username, `name`, `password`, createtime, creator, `role` ) values (#{username,jdbcType=VARCHAR}, #{name,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}, #{createtime,jdbcType=TIMESTAMP}, #{creator,jdbcType=INTEGER}, #{role,jdbcType=VARCHAR} ) </insert> <insert id="insertSelective" keyColumn="user_id" keyProperty="userId" parameterType="com.example.demo.model.User" useGeneratedKeys="true"> insert into user <trim prefix="(" suffix=")" suffixOverrides=","> <if test="username != null"> username, </if> <if test="name != null"> `name`, </if> <if test="password != null"> `password`, </if> <if test="createtime != null"> createtime, </if> <if test="creator != null"> creator, </if> <if test="role != null"> `role`, </if> </trim> <trim prefix="values (" suffix=")" suffixOverrides=","> <if test="username != null"> #{username,jdbcType=VARCHAR}, </if> <if test="name != null"> #{name,jdbcType=VARCHAR}, </if> <if test="password != null"> #{password,jdbcType=VARCHAR}, </if> <if test="createtime != null"> #{createtime,jdbcType=TIMESTAMP}, </if> <if test="creator != null"> #{creator,jdbcType=INTEGER}, </if> <if test="role != null"> #{role,jdbcType=VARCHAR}, </if> </trim> </insert> <select id="countByExample" parameterType="com.example.demo.model.UserExample" resultType="java.lang.Long"> select count(*) from user <if test="_parameter != null"> <include refid="Example_Where_Clause" /> </if> </select> <update id="updateByExampleSelective" parameterType="map"> update user <set> <if test="record.userId != null"> user_id = #{record.userId,jdbcType=INTEGER}, </if> <if test="record.username != null"> username = #{record.username,jdbcType=VARCHAR}, </if> <if test="record.name != null"> `name` = #{record.name,jdbcType=VARCHAR}, </if> <if test="record.password != null"> `password` = #{record.password,jdbcType=VARCHAR}, </if> <if test="record.createtime != null"> createtime = #{record.createtime,jdbcType=TIMESTAMP}, </if> <if test="record.creator != null"> creator = #{record.creator,jdbcType=INTEGER}, </if> <if test="record.role != null"> `role` = #{record.role,jdbcType=VARCHAR}, </if> </set> <if test="_parameter != null"> <include refid="Update_By_Example_Where_Clause" /> </if> </update> <update id="updateByExample" parameterType="map"> update user set user_id = #{record.userId,jdbcType=INTEGER}, username = #{record.username,jdbcType=VARCHAR}, `name` = #{record.name,jdbcType=VARCHAR}, `password` = #{record.password,jdbcType=VARCHAR}, createtime = #{record.createtime,jdbcType=TIMESTAMP}, creator = #{record.creator,jdbcType=INTEGER}, `role` = #{record.role,jdbcType=VARCHAR} <if test="_parameter != null"> <include refid="Update_By_Example_Where_Clause" /> </if> </update> <update id="updateByPrimaryKeySelective" parameterType="com.example.demo.model.User"> update user <set> <if test="name != null"> `name` = #{name,jdbcType=VARCHAR}, </if> <if test="password != null"> `password` = #{password,jdbcType=VARCHAR}, </if> <if test="createtime != null"> createtime = #{createtime,jdbcType=TIMESTAMP}, </if> <if test="creator != null"> creator = #{creator,jdbcType=INTEGER}, </if> <if test="role != null"> `role` = #{role,jdbcType=VARCHAR}, </if> </set> where user_id = #{userId,jdbcType=INTEGER} and username = #{username,jdbcType=VARCHAR} </update> <update id="updateByPrimaryKey" parameterType="com.example.demo.model.User"> update user set `name` = #{name,jdbcType=VARCHAR}, `password` = #{password,jdbcType=VARCHAR}, createtime = #{createtime,jdbcType=TIMESTAMP}, creator = #{creator,jdbcType=INTEGER}, `role` = #{role,jdbcType=VARCHAR} where user_id = #{userId,jdbcType=INTEGER} and username = #{username,jdbcType=VARCHAR} </update> </mapper>

测试结果

如果报错:org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.example.demo.mapper.UserMapper.selectByPrimaryKey

2020-11-09 16:27:59.053 INFO 13776 --- [nio-8080-exec-3] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet' 2020-11-09 16:27:59.053 INFO 13776 --- [nio-8080-exec-3] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet' 2020-11-09 16:27:59.059 INFO 13776 --- [nio-8080-exec-3] o.s.web.servlet.DispatcherServlet : Completed initialization in 6 ms 2020-11-09 16:27:59.142 ERROR 13776 --- [nio-8080-exec-3] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.example.demo.mapper.UserMapper.selectByPrimaryKey] with root cause org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.example.demo.mapper.UserMapper.selectByPrimaryKey at org.apache.ibatis.binding.MapperMethod$SqlCommand.<init>(MapperMethod.java:235) ~[mybatis-3.5.5.jar:3.5.5] at org.apache.ibatis.binding.MapperMethod.<init>(MapperMethod.java:53) ~[mybatis-3.5.5.jar:3.5.5] at org.apache.ibatis.binding.MapperProxy.lambda$cachedInvoker$0(MapperProxy.java:115) ~[mybatis-3.5.5.jar:3.5.5] at java.util.concurrent.ConcurrentHashMap.computeIfAbsent(ConcurrentHashMap.java:1660) ~[na:1.8.0_131] at org.apache.ibatis.binding.MapperProxy.cachedInvoker(MapperProxy.java:102) ~[mybatis-3.5.5.jar:3.5.5] at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:85) ~[mybatis-3.5.5.jar:3.5.5] at com.sun.proxy.$Proxy53.selectByPrimaryKey(Unknown Source) ~[na:na] at com.example.demo.service.impl.UserServiceImpl.findUserByPrimaryKey(UserServiceImpl.java:26) ~[classes/:na] at com.example.demo.controller.UserController.findUserByPrimaryKey(UserController.java:38) ~[classes/:na] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_131] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_131] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_131] at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_131] at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190) ~[spring-web-5.2.9.RELEASE.jar:5.2.9.RELEASE] at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138) ~[spring-web-5.2.9.RELEASE.jar:5.2.9.RELEASE] at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:105) ~[spring-webmvc-5.2.9.RELEASE.jar:5.2.9.RELEASE] at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:878) ~[spring-webmvc-5.2.9.RELEASE.jar:5.2.9.RELEASE] at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:792) ~[spring-webmvc-5.2.9.RELEASE.jar:5.2.9.RELEASE] at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.2.9.RELEASE.jar:5.2.9.RELEASE] at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040) ~[spring-webmvc-5.2.9.RELEASE.jar:5.2.9.RELEASE] at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943) ~[spring-webmvc-5.2.9.RELEASE.jar:5.2.9.RELEASE] at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) ~[spring-webmvc-5.2.9.RELEASE.jar:5.2.9.RELEASE] at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898) ~[spring-webmvc-5.2.9.RELEASE.jar:5.2.9.RELEASE] at javax.servlet.http.HttpServlet.service(HttpServlet.java:626) ~[tomcat-embed-core-9.0.38.jar:4.0.FR] at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) ~[spring-webmvc-5.2.9.RELEASE.jar:5.2.9.RELEASE] at javax.servlet.http.HttpServlet.service(HttpServlet.java:733) ~[tomcat-embed-core-9.0.38.jar:4.0.FR] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-9.0.38.jar:9.0.38] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.38.jar:9.0.38] at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.38.jar:9.0.38] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.38.jar:9.0.38] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.38.jar:9.0.38] at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-5.2.9.RELEASE.jar:5.2.9.RELEASE] at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.9.RELEASE.jar:5.2.9.RELEASE] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.38.jar:9.0.38] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.38.jar:9.0.38] at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-5.2.9.RELEASE.jar:5.2.9.RELEASE] at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.9.RELEASE.jar:5.2.9.RELEASE] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.38.jar:9.0.38] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.38.jar:9.0.38] at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-5.2.9.RELEASE.jar:5.2.9.RELEASE] at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.9.RELEASE.jar:5.2.9.RELEASE] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.38.jar:9.0.38] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.38.jar:9.0.38] at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) ~[tomcat-embed-core-9.0.38.jar:9.0.38] at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97) [tomcat-embed-core-9.0.38.jar:9.0.38] at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541) [tomcat-embed-core-9.0.38.jar:9.0.38] at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143) [tomcat-embed-core-9.0.38.jar:9.0.38] at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) [tomcat-embed-core-9.0.38.jar:9.0.38] at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78) [tomcat-embed-core-9.0.38.jar:9.0.38] at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) [tomcat-embed-core-9.0.38.jar:9.0.38] at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:374) [tomcat-embed-core-9.0.38.jar:9.0.38] at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) [tomcat-embed-core-9.0.38.jar:9.0.38] at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868) [tomcat-embed-core-9.0.38.jar:9.0.38] at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1590) [tomcat-embed-core-9.0.38.jar:9.0.38] at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-9.0.38.jar:9.0.38] at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_131] at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_131] at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-9.0.38.jar:9.0.38] at java.lang.Thread.run(Thread.java:748) [na:1.8.0_131]

原因:mapper接口找不到对应的mapper.xml文件 

解决:在配置文件中,增加配置mybatis.mapper-locations,作用:扫描Mapper接口对应的XML文件

spring.datasource.url=jdbc:mysql://xxxx:3306/xxxx?characterEncoding=UTF-8&serverTimezone=Asia/Shanghai spring.datasource.username=xxx spring.datasource.password=xxxx #扫描Mapper接口对应的XML文件 mybatis.mapper-locations=classpath:mybatis-mapper/*.xml mybatis.type-aliases-package=com.example.demo.model;

 

最新回复(0)