06_MyBatis,Spring,SpringMVC整合

简介:  项目结构 Spring的配置: beans.xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans"     x

  1. 项目结构

  1. Spring的配置:

beans.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:mvc="http://www.springframework.org/schema/mvc"

    xmlns:context="http://www.springframework.org/schema/context"

    xmlns:aop="http://www.springframework.org/schema/aop"

    xmlns:tx="http://www.springframework.org/schema/tx"

    xsi:schemaLocation="http://www.springframework.org/schema/beans

       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd

       http://www.springframework.org/schema/mvc

       http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd

       http://www.springframework.org/schema/context

       http://www.springframework.org/schema/context/spring-context-3.0.xsd

       http://www.springframework.org/schema/aop

       http://www.springframework.org/schema/aop/spring-aop-3.0.xsd

       http://www.springframework.org/schema/tx

       http://www.springframework.org/schema/tx/spring-tx-3.0.xsd ">                      

      

       <context:component-scan base-package="com.rl"/>

      

       <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">

           <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>

           <property name="url" value="jdbc:mysql://localhost:3306/mybatis"></property>

           <property name="username" value="root"></property>

           <property name="password" value="123456"></property>

       </bean>

      

       <!--

           使用spring来管理sqlSessionFactory

        -->

       <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">

           <property name="configLocation" value="classpath:sqlMapConfig.xml"></property>

           <property name="dataSource" ref="dataSource"></property>

       </bean>

      

       <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

           <property name="dataSource" ref="dataSource"></property>

       </bean>

      

       <tx:advice id="txAdvice" transaction-manager="txManager">

           <tx:attributes>

              <tx:method name="save*" propagation="REQUIRED"/>

              <tx:method name="update*" propagation="REQUIRED"/>

              <tx:method name="delete*" propagation="REQUIRED"/>

              <tx:method name="select*" read-only="true"/>

           </tx:attributes>

       </tx:advice>

      

       <aop:config>

           <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.rl.service..*.*(..))"/>

       </aop:config>

</beans>

  1. springmvc.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:mvc="http://www.springframework.org/schema/mvc"

    xmlns:context="http://www.springframework.org/schema/context"

    xmlns:aop="http://www.springframework.org/schema/aop"

    xmlns:tx="http://www.springframework.org/schema/tx"

    xsi:schemaLocation="http://www.springframework.org/schema/beans

       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd

       http://www.springframework.org/schema/mvc

       http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd

       http://www.springframework.org/schema/context

       http://www.springframework.org/schema/context/spring-context-3.0.xsd

       http://www.springframework.org/schema/aop

       http://www.springframework.org/schema/aop/spring-aop-3.0.xsd

       http://www.springframework.org/schema/tx

       http://www.springframework.org/schema/tx/spring-tx-3.0.xsd ">                       

      

       <context:component-scan base-package="com.rl.controller"/>

       <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">

           <property name="prefix" value="/WEB-INF/jsp/"></property>

           <property name="suffix" value=".jsp"></property>

       </bean>

</beans>

  1. web.xml的配置内容如下:

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"

    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"

    id="WebApp_ID" version="2.5">

   

    <listener>

       <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

    </listener>

    <context-param>

       <param-name>contextConfigLocation</param-name>

       <param-value>classpath:beans.xml</param-value>

    </context-param>

   

    <servlet>

       <servlet-name>springmvc</servlet-name>

       <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

       <init-param>

           <param-name>contextConfigLocation</param-name>

           <param-value>classpath:springmvc.xml</param-value>

       </init-param>

    </servlet>

    <servlet-mapping>

       <servlet-name>springmvc</servlet-name>

       <url-pattern>*.do</url-pattern>

    </servlet-mapping>

   

    <filter>

        <filter-name>SpringCharacterEncodingFilter</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>

    </filter>

    <filter-mapping>

        <filter-name>SpringCharacterEncodingFilter</filter-name>

        <url-pattern>*.do</url-pattern>

    </filter-mapping>

   

</web-app>

5  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

  1. sqlMapConfig.xml

<?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>

   <typeAliases>

      <typeAlias type="com.rl.model.Person" alias="person"/>

   </typeAliases>

   <mappers>

      <mapper resource="com/rl/mapper/PersonMapper.xml" />

   </mappers>

</configuration>

PersonMapper.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">

<!--

namespace:命名空间,用来唯一标识一个映射文件,命名规范就是当前的文件的包加上文件名

 -->

<mapper namespace="com.rl.mapper.PersonMapper">

 

   <resultMap type="person" id="BaseResultMap">

      <!--

         column:库表的字段

         property:库表所有映射的实体类中属性名

       -->

      <id column="person_id" property="personId"/>

      <result column="name" property="name"/>

      <result column="gender" property="gender"/>

      <result column="person_addr" property="personAddr"/>

      <result column="birthday" property="birthday"/>

   </resultMap>

  

   <!--

      公用的sql片段,也可以接收参数动态sql,所有的sql可以

    -->

   <sql id="columns">

      PERSON_ID, NAME, GENDER, PERSON_ADDR, BIRTHDAY

   </sql>

  

   <!--

      根据id来查询一个Person的数据

      sql语句接收参数的一个语法#{},如果接收的是一个{}中的内容任意select * from person_test t where t.ID = ?,使用预编译方式生成sql

      id:sql语句的唯一的标识不能重复

      parameterType:sql要接收的数据类型

      resultTypesql所返回的数据类型

    -->

    

    <!--

      实际项目中数据库的表的字段一般由多个单词来构成 由下划线来分隔多个单词 person_addr

      javamodel的实体类中的属性多个单词的命名规范是驼峰模式personAddr

     -->

     <!--

       useCache:控制当前的这个sql是否使用二级缓存

      -->

    <select id="selectPersonById" parameterType="int" resultMap="BaseResultMap" useCache="true">

      select * from person t where t.person_id = #{id}

    </select>

    

   <!-- 库表变更 -->

   <insert id="insert" parameterType="person">

     

      <selectKey keyProperty="personId" order="AFTER" resultType="int">

         select LAST_INSERT_ID()

      </selectKey>

      insert into person (person_id, name, gender, person_addr, birthday)

      values(#{personId}, #{name}, #{gender}, #{personAddr}, #{birthday})

   </insert>

  

  

   <!--

      删除的sql不能使用别名

    -->

   <delete id="delete" parameterType="int">

      delete from person where person_id = #{personId}

   </delete>

  

   <!-- 动态sql -->

   <!--

      map.put("name", "");

      map.put("gender", "0");

      map.put("personAddr", "东京")

      map.put("birthday", new Date());

     

      <where>会自动处理and 第一个and可以不写,其他的and必须要写

    -->

   <select id="selectPersonByCondition" parameterType="map" resultMap="BaseResultMap">

      select * from person t

      <where>

         <if test="name != null">

             t.name like '%${name}%'

         </if>

         <if test="gender != null">

            and t.gender = #{gender}

         </if>

         <if test="personAddr != null">

            and t.person_addr like '%${personAddr}%'

         </if>

         <if test="birthday != null">

            <![CDATA[

                and t.birthday < #{birthday}

            ]]>

         </if>

      </where>

   </select>

  

  

   <!--

      动态修改

      <set>标签可以去掉最后一个逗号

     

      flushCache:二级缓存的刷新的配置:默认是true:会刷新,如果false就不刷新缓存

    -->

   <update id="dynamicUpdate" parameterType="person" flushCache="false">

      update person t

      <set>

         <if test="name != null">

            t.name = #{name},

         </if>

         <if test="gender != null">

            t.gender = #{gender},

         </if>

         <if test="personAddr != null">

            t.person_addr = #{personAddr},

         </if>

         <if test="birthday != null">

            t.birthday = #{birthday}

         </if>

      </set>

      where t.person_id = #{personId}

   </update>

  

</mapper>

6  Person.java的内容如下:

package com.rl.model;

 

import java.io.Serializable;

import java.util.Date;

 

public class Person implements Serializable{

         private static final long serialVersionUID = 7728191033619971201L;

         private Integer personId;

         private String name;

         private String gender;

         private String personAddr;

         private Date birthday;

        

         public Integer getPersonId() {

                   return personId;

         }

 

         public void setPersonId(Integer personId) {

                   this.personId = personId;

         }

 

         public String getName() {

                   return name;

         }

 

         public void setName(String name) {

                   this.name = name;

         }

 

         public String getGender() {

                   return gender;

         }

 

         public void setGender(String gender) {

                   this.gender = gender;

         }

 

         public String getPersonAddr() {

                   return personAddr;

         }

 

         public void setPersonAddr(String personAddr) {

                   this.personAddr = personAddr;

         }

 

         public Date getBirthday() {

                   return birthday;

         }

 

         public void setBirthday(Date birthday) {

                   this.birthday = birthday;

         }

}

7  PersonDao.java

package com.rl.dao;

 

import java.util.List;

import java.util.Map;

 

import com.rl.model.Person;

 

public interface PersonDao {

         public void save(Person person);

         public Person selectPersonById(Integer personId);

         public void update(Person person);

         public void delete(Integer personId);

         public List<Person> selectPersonByCondition(Map<String, Object> map);

}

8  PersonDaoImpl.java的内容如下:

package com.rl.dao.impl;

 

import java.util.List;

import java.util.Map;

 

import org.mybatis.spring.support.SqlSessionDaoSupport;

import org.springframework.stereotype.Repository;

 

import com.rl.dao.PersonDao;

import com.rl.model.Person;

@Repository

public class PersonDaoImpl extends SqlSessionDaoSupport implements PersonDao {

         //命名空间

         String ns = "com.rl.mapper.PersonMapper.";

         @Override

         public void save(Person person) {

                   this.getSqlSession().insert(ns+"insert", person);

         }

 

         @Override

         public Person selectPersonById(Integer personId) {

                   return (Person) this.getSqlSession().selectOne(ns+"selectPersonById", personId);

         }

 

         @Override

         public void update(Person person) {

                   this.getSqlSession().update(ns+"dynamicUpdate", person);

         }

 

         @Override

         public void delete(Integer personId) {

                   this.getSqlSession().delete(ns+"delete", personId);

         }

 

         @SuppressWarnings("unchecked")

         @Override

         public List<Person> selectPersonByCondition(Map<String, Object> map) {

                   return this.getSqlSession().selectList(ns+"selectPersonByCondition", map);

         }

 

}

9  PersonService.java

package com.rl.service;

 

import java.util.List;

import java.util.Map;

 

import com.rl.model.Person;

 

public interface PersonService {

         public void save(Person person);

         public Person selectPersonById(Integer personId);

         public void update(Person person);

         public void delete(Integer personId);

         public List<Person> selectPersonByCondition(Map<String, Object> map);

}

10  PersonServiceImpl.java

package com.rl.service.impl;

 

import java.util.List;

import java.util.Map;

 

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

 

import com.rl.dao.PersonDao;

import com.rl.model.Person;

import com.rl.service.PersonService;

@Service

public class PersonServiceImpl implements PersonService {

 

         @Autowired

         private PersonDao personDao;

        

         @Override

         public void save(Person person) {

                   personDao.save(person);

         }

 

         @Override

         public Person selectPersonById(Integer personId) {

                   return personDao.selectPersonById(personId);

         }

 

         @Override

         public void update(Person person) {

                   personDao.update(person);

         }

 

         @Override

         public void delete(Integer personId) {

                   personDao.delete(personId);

         }

 

         @Override

         public List<Person> selectPersonByCondition(Map<String, Object> map) {

                   return personDao.selectPersonByCondition(map);

         }

}

11  PersonController.java的内容如下:

package com.rl.controller;

 

import java.text.SimpleDateFormat;

import java.util.Date;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

 

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.beans.propertyeditors.CustomDateEditor;

import org.springframework.stereotype.Controller;

import org.springframework.ui.Model;

import org.springframework.web.bind.ServletRequestDataBinder;

import org.springframework.web.bind.annotation.InitBinder;

import org.springframework.web.bind.annotation.RequestMapping;

 

import com.rl.model.Person;

import com.rl.service.PersonService;

 

@Controller

@RequestMapping("/person")

public class PersonController {

        

         @Autowired

         private PersonService personService;

        

         /**

          * 跳转到添加页面

          */

         @RequestMapping("/toSave.do")

         public String toSave(){

                   return "add";

         }

        

         /**

          * 添加Person

          */

         @RequestMapping("/save.do")

         public String save(Person person){

                   personService.save(person);

                   return "redirect:listPerson.do";

         }

        

         /**

          * 查询Person

          */

         @RequestMapping("/getPerson.do")

         public String getPerson(Integer personId, Model model){

                   Person person = personService.selectPersonById(personId);

                   model.addAttribute("person", person);

                   return "update";

         }

         /**

          * 修改Person

          */

         @RequestMapping("/update.do")

         public String update(Person person){

                   personService.update(person);

                   return "redirect:listPerson.do";

         }

        

         /**

          * 删除

          */

         @RequestMapping("/delete.do")

         public String delete(Integer personId){

                   personService.delete(personId);

                   return "redirect:listPerson.do";

         }

 

         /**

          * 动态条件组合查询

          */

         @RequestMapping("/listPerson.do")

         public String listPerson(String name, String gender,

                            String personAddr, Date birthday, Model model){

                   Map<String, Object> map = new HashMap<String,Object>();

                   if(name != null && "".equals(name.trim())){

                            name = null;

                   }

                   if(gender != null && "".equals(gender.trim())){

                            gender = null;

                   }

                   if(personAddr != null && "".equals(personAddr.trim())){

                            personAddr = null;

                   }

                   map.put("name", name);

                   map.put("gender", gender);

                   map.put("personAddr", personAddr);

                   map.put("birthday", birthday);

                   List<Person> pList = personService.selectPersonByCondition(map);

                   model.addAttribute("pList", pList);

                   model.addAttribute("name", name);

                   model.addAttribute("gender", gender);

                   model.addAttribute("personAddr", personAddr);

                   model.addAttribute("birthday", birthday);

                  

                   return "list";

         }

        

         @InitBinder

         public void initBinder(ServletRequestDataBinder binder){

                   binder.registerCustomEditor(Date.class,

                                     new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));

         }

}

12  add.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<%

String path = request.getContextPath();

String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

%>

<%@taglib uri="http://java.sun.com/jsp/jstl/core"  prefix="c"%>

<%@taglib uri="http://java.sun.com/jsp/jstl/fmt"  prefix="f"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

  <head>

    <base href="<%=basePath%>">

   

    <title>My JSP 'list.jsp' starting page</title>

   

   <meta http-equiv="pragma" content="no-cache">

   <meta http-equiv="cache-control" content="no-cache">

   <meta http-equiv="expires" content="0">   

   <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">

   <meta http-equiv="description" content="This is my page">

   <!--

   <link rel="stylesheet" type="text/css" href="styles.css">

   -->

 

  </head>

 

  <body>

    <form action="person/save.do" method="post">

        <table width="80%" align="center">

          <tr>

             <td><label>姓名:</label><input type="text" name="name" ></td>

             <td><label>性别:</label>

                <select name="gender" >

                   <option value="">请选择</option>

                   <option value="0"  ></option>

                   <option value="1"  ></option>

                </select>

             </td>

             <td><label>地址:</label><input type="text" name="personAddr" ></td>

             <td><label>生日:</label><input type="text" name="birthday"></td>

             <td><input type="submit" value="保存"></td>

          </tr>

       </table>

    </form>

  </body>

</html>

13 list.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<%

String path = request.getContextPath();

String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

%>

<%@taglib uri="http://java.sun.com/jsp/jstl/core"  prefix="c"%>

<%@taglib uri="http://java.sun.com/jsp/jstl/fmt"  prefix="f"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

  <head>

    <base href="<%=basePath%>">

   

    <title>My JSP 'list.jsp' starting page</title>

   

   <meta http-equiv="pragma" content="no-cache">

   <meta http-equiv="cache-control" content="no-cache">

   <meta http-equiv="expires" content="0">   

   <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">

   <meta http-equiv="description" content="This is my page">

   <!--

   <link rel="stylesheet" type="text/css" href="styles.css">

   -->

   <script type="text/javascript">

      function delPerson(personId){

         if(confirm("真删吗?")){

            window.location.href="person/delete.do?personId="+personId;

         }

      }

   </script>

  </head>

 

  <body>

    <form action="person/listPerson.do" method="post">

        <table width="80%" align="center">

          <tr>

             <td><label>姓名:</label><input type="text" name="name" value="${name }"></td>

             <td><label>性别:</label>

                <select name="gender" >

                   <option value="">请选择</option>

                   <option value="0" <c:if test="${gender == '0' }">selected</c:if> ></option>

                   <option value="1" <c:if test="${gender == '1' }">selected</c:if> ></option>

                </select>

             </td>

             <td><label>地址:</label><input type="text" name="personAddr" value="${personAddr }"></td>

             <td><label>生日:</label><input type="text" name="birthday" value="<f:formatDate value="${birthday }" pattern="yyyy-MM-dd"/>"></td>

             <td><input type="submit" value="查询"></td>

          </tr>

       </table>

    </form>

    <table align="center" width="80%">

       <tr>

          <td><a href="person/toSave.do">添加</a></td>

       </tr>

    </table>

   

   <table width="80%" align="center" border="1">

       <tr>

          <th>姓名</th>

          <th>性别</th>

          <th>地址</th>

          <th>生日</th>

          <th>操作</th>

       </tr>

       <c:forEach items="${pList }" var="person">

          <tr>

             <td>${person.name }</td>

             <td>

                <c:if test="${person.gender == '0' }"></c:if>

                <c:if test="${person.gender == '1' }"></c:if>

            </td>

             <td>${person.personAddr }</td>

             <td><f:formatDate value="${person.birthday }" pattern="yyyy-MM-dd"/> </td>

             <td><a href="person/getPerson.do?personId=${person.personId }">修改</a>

            

             <a href="javascript:void(0)" onclick="delPerson(${person.personId})">删除</a></td>

          </tr>

       </c:forEach>

      

   </table>

  </body>

</html>

14 update.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<%

String path = request.getContextPath();

String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

%>

<%@taglib uri="http://java.sun.com/jsp/jstl/core"  prefix="c"%>

<%@taglib uri="http://java.sun.com/jsp/jstl/fmt"  prefix="f"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

  <head>

    <base href="<%=basePath%>">

   

    <title>My JSP 'list.jsp' starting page</title>

   

   <meta http-equiv="pragma" content="no-cache">

   <meta http-equiv="cache-control" content="no-cache">

   <meta http-equiv="expires" content="0">   

   <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">

   <meta http-equiv="description" content="This is my page">

   <!--

   <link rel="stylesheet" type="text/css" href="styles.css">

   -->

 

  </head>

 

  <body>

    <form action="person/update.do" method="post">

    <input type="hidden" name="personId" value="${person.personId }">

        <table width="80%" align="center">

         

          <tr>

             <td><label>姓名:</label><input type="text" name="name" value="${person.name }"></td>

             <td><label>性别:</label>

                <select name="gender" >

                   <option value="">请选择</option>

                   <option value="0" <c:if test="${person.gender == '0' }">selected</c:if> ></option>

                   <option value="1" <c:if test="${person.gender == '1' }">selected</c:if> ></option>

                </select>

             </td>

             <td><label>地址:</label><input type="text" name="personAddr" value="${person.personAddr }"></td>

             <td><label>生日:</label><input type="text" name="birthday" value="<f:formatDate value="${person.birthday }" pattern="yyyy-MM-dd"/>"></td>

             <td><input type="submit" value="修改"></td>

          </tr>

       </table>

    </form>

 

      

  </body>

</html>

 

 

 

 

 

 

目录
相关文章
|
2月前
|
前端开发 Java 微服务
《深入理解Spring》:Spring、Spring MVC与Spring Boot的深度解析
Spring Framework是Java生态的基石,提供IoC、AOP等核心功能;Spring MVC基于其构建,实现Web层MVC架构;Spring Boot则通过自动配置和内嵌服务器,极大简化了开发与部署。三者层层演进,Spring Boot并非替代,而是对前者的高效封装与增强,适用于微服务与快速开发,而深入理解Spring Framework有助于更好驾驭整体技术栈。
|
9月前
|
XML Java 数据库连接
微服务——SpringBoot使用归纳——Spring Boot集成MyBatis——基于 xml 的整合
本教程介绍了基于XML的MyBatis整合方式。首先在`application.yml`中配置XML路径,如`classpath:mapper/*.xml`,然后创建`UserMapper.xml`文件定义SQL映射,包括`resultMap`和查询语句。通过设置`namespace`关联Mapper接口,实现如`getUserByName`的方法。Controller层调用Service完成测试,访问`/getUserByName/{name}`即可返回用户信息。为简化Mapper扫描,推荐在Spring Boot启动类用`@MapperScan`注解指定包路径避免逐个添加`@Mapper`
459 0
|
6月前
|
Java 数据库连接 数据库
Spring boot 使用mybatis generator 自动生成代码插件
本文介绍了在Spring Boot项目中使用MyBatis Generator插件自动生成代码的详细步骤。首先创建一个新的Spring Boot项目,接着引入MyBatis Generator插件并配置`pom.xml`文件。然后删除默认的`application.properties`文件,创建`application.yml`进行相关配置,如设置Mapper路径和实体类包名。重点在于配置`generatorConfig.xml`文件,包括数据库驱动、连接信息、生成模型、映射文件及DAO的包名和位置。最后通过IDE配置运行插件生成代码,并在主类添加`@MapperScan`注解完成整合
1026 1
Spring boot 使用mybatis generator 自动生成代码插件
|
6月前
|
Java 数据库连接 API
Java 对象模型现代化实践 基于 Spring Boot 与 MyBatis Plus 的实现方案深度解析
本文介绍了基于Spring Boot与MyBatis-Plus的Java对象模型现代化实践方案。采用Spring Boot 3.1.2作为基础框架,结合MyBatis-Plus 3.5.3.1进行数据访问层实现,使用Lombok简化PO对象,MapStruct处理对象转换。文章详细讲解了数据库设计、PO对象实现、DAO层构建、业务逻辑封装以及DTO/VO转换等核心环节,提供了一个完整的现代化Java对象模型实现案例。通过分层设计和对象转换,实现了业务逻辑与数据访问的解耦,提高了代码的可维护性和扩展性。
230 1
|
5月前
|
SQL Java 数据库连接
Spring、SpringMVC 与 MyBatis 核心知识点解析
我梳理的这些内容,涵盖了 Spring、SpringMVC 和 MyBatis 的核心知识点。 在 Spring 中,我了解到 IOC 是控制反转,把对象控制权交容器;DI 是依赖注入,有三种实现方式。Bean 有五种作用域,单例 bean 的线程安全问题及自动装配方式也清晰了。事务基于数据库和 AOP,有失效场景和七种传播行为。AOP 是面向切面编程,动态代理有 JDK 和 CGLIB 两种。 SpringMVC 的 11 步执行流程我烂熟于心,还有那些常用注解的用法。 MyBatis 里,#{} 和 ${} 的区别很关键,获取主键、处理字段与属性名不匹配的方法也掌握了。多表查询、动态
157 0
|
6月前
|
SQL Java 数据库
解决Java Spring Boot应用中MyBatis-Plus查询问题的策略。
保持技能更新是侦探的重要素质。定期回顾最佳实践和新技术。比如,定期查看MyBatis-Plus的更新和社区的最佳做法,这样才能不断提升查询效率和性能。
238 1
|
11月前
|
SQL Java 数据库连接
对Spring、SpringMVC、MyBatis框架的介绍与解释
Spring 框架提供了全面的基础设施支持,Spring MVC 专注于 Web 层的开发,而 MyBatis 则是一个高效的持久层框架。这三个框架结合使用,可以显著提升 Java 企业级应用的开发效率和质量。通过理解它们的核心特性和使用方法,开发者可以更好地构建和维护复杂的应用程序。
555 29
|
9月前
|
XML Java 数据库连接
微服务——SpringBoot使用归纳——Spring Boot集成MyBatis——基于注解的整合
本文介绍了Spring Boot集成MyBatis的两种方式:基于XML和注解的形式。重点讲解了注解方式,包括@Select、@Insert、@Update、@Delete等常用注解的使用方法,以及多参数时@Param注解的应用。同时,针对字段映射不一致的问题,提供了@Results和@ResultMap的解决方案。文章还提到实际项目中常结合XML与注解的优点,灵活使用两者以提高开发效率,并附带课程源码供下载学习。
706 0
|
9月前
|
Java 数据库连接 数据库
微服务——SpringBoot使用归纳——Spring Boot集成MyBatis——MyBatis 介绍和配置
本文介绍了Spring Boot集成MyBatis的方法,重点讲解基于注解的方式。首先简述MyBatis作为持久层框架的特点,接着说明集成时的依赖导入,包括`mybatis-spring-boot-starter`和MySQL连接器。随后详细展示了`properties.yml`配置文件的内容,涵盖数据库连接、驼峰命名规范及Mapper文件路径等关键设置,帮助开发者快速上手Spring Boot与MyBatis的整合开发。
1122 0
|
11月前
|
SQL JavaScript Java
Spring Boot 3 整合 Mybatis-Plus 实现数据权限控制
本文介绍了如何在Spring Boot 3中整合MyBatis-Plus实现数据权限控制,通过使用MyBatis-Plus提供的`DataPermissionInterceptor`插件,在不破坏原有代码结构的基础上实现了细粒度的数据访问控制。文中详细描述了自定义注解`DataScope`的使用方法、`DataPermissionHandler`的具体实现逻辑,以及根据用户的不同角色和部门动态添加SQL片段来限制查询结果。此外,还展示了基于Spring Boot 3和Vue 3构建的前后端分离快速开发框架的实际应用案例,包括项目的核心功能模块如用户管理、角色管理等,并提供Gitee上的开源仓库
2055 11