Live2D

SSM2021

Mybatis(ieda)

  1. Maven仓库:

mavenRepositroy

  1. 数据库:
CREATE TABLE `user`(
`id`  INT(20) NOT NULL PRIMARY KEY,
`name`  VARCHAR(30) DEFAULT  NULL,
`pwd` VARCHAR(30) DEFAULT NULL
)ENGINE=INNODB CHARSET=utf8;

INSERT INTO `user`(`id`,`name`,`pwd`) VALUES
(1,'lix','123456'),
(2,'admin','123456'),
(3,'root','123456')
  1. 导入依赖
 <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version> 5.1.47</version>
        </dependency>
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.2</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.2</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.4</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.5</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.12.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.2.8.RELEASE</version>
        </dependency>
    </dependencies>
  1. 1、添加applicationContext表头

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
            https://www.springframework.org/schema/beans/spring-beans.xsd">
    
    
    
    
    </beans>
    

    4.2、添加mybatis配置文件-----表头:

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

4.3、添加database.properties文件

jdbc.driver=com.mysql.cj.jdbc.Driver
#如果使用的是MySQL8.0+ ,需要增加一个时区的配置  &serverTime=Asia/Shanghai
jdbc.url=jdbc:mysql://localhost:3306/ssmbuild?useSSL=true&useUnicode=true&characterEncoding=utf-8
jdbc.username=******
jdbc.password=******

4.4、添加mapper表头

<?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="">
    
</mapper>

4.5、编写dao层-----

  • 接口
package com.lix.dao;

import com.lix.pojo.Books;
import org.apache.ibatis.annotations.Param;

import java.util.List;

public interface BookMapper {
    int addBook(Books books);
    int deleteBookById(@Param("bookId") int id);
    int updateBook(Books books);
    Books queryBookById(@Param("bookId") int id);
    List<Books> queryAllBook();
}

  • 实现

    <?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.lix.dao.BookMapper">
    
        <insert id="addBook" parameterType="Books">
            insert into ssmbuild.books (bookName,bookCounts,detail)
            values (#{bookName},#{bookCounts},#{detail});
        </insert>
    
        <delete id="deleteBookById" parameterType="int">
            delete from ssmbuild.books where bookID = #{bookId}
        </delete>
    
        <update id="updateBook" parameterType="Books">
            update ssmbuild.books
            set bookName=#{bookName},bookCounts=#{bookCounts},detail=#{detail}
            where bookID=#{bookID}
        </update>
    
        <select id="queryBookById" resultType="Books">
            select * from ssmbuild.books
            where bookID = #{bookId}
        </select>
    
        <select id="queryAllBook" resultType="Books">
            select * from ssmbuild.books
        </select>
    
    </mapper>
    

    4.6、编写service层------

    • 接口
    package com.lix.service;
    
    import com.lix.pojo.Books;
    import org.apache.ibatis.annotations.Param;
    
    import java.util.List;
    
    public interface BookService {
    
        int addBook(Books books);
        int deleteBookById(int id);
        int updateBook(Books books);
        Books queryBookById(int id);
        List<Books> queryAllBook();
    
    }
    
    
    • 实现

      package com.lix.service;
      
      import com.lix.dao.BookMapper;
      import com.lix.pojo.Books;
      
      import java.util.List;
      
      public class BookServiceImpl implements BookService {
      
          private BookMapper bookMapper;
      
          public void setBookMapper(BookMapper bookMapper) {
              this.bookMapper = bookMapper;
          }
      
          public int addBook(Books books) {
              return bookMapper.addBook(books);
          }
      
          public int deleteBookById(int id) {
              return bookMapper.deleteBookById(id);
          }
      
          public int updateBook(Books books) {
              return bookMapper.updateBook(books);
          }
      
          public Books queryBookById(int id) {
              return bookMapper.queryBookById(id);
          }
      
          public List<Books> queryAllBook() {
              return bookMapper.queryAllBook();
          }
      }
      
      

      ------mybatis层完结

      ------spring层开始-----

5.spring整合dao层

<?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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">

<!--    关联数据库配置文件-->

    <context:property-placeholder location="classpath:database.properties"/>
<!--    连接池
        dbcp:半自动化操作,不能自动连接
        c3p0:自动化操作(自动化的加载配置文件,并且可以自动设置到对象中!)
        druid:
        hikari:
-->

    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"/>
        <property name="jdbcUrl" value="${jdbc.url}"/>
        <property name="user" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>

<!--        c3p0的私有属性-->
        <property name="maxPoolSize" value="30"/>
        <property name="minPoolSize" value="10"/>
<!--        关闭连接后不自动commit-->
        <property name="autoCommitOnClose" value="false"/>
<!--        获取连接超时时间-->
        <property name="checkoutTimeout" value="10000"/>
<!--        当  获取连接失败 重试次数-->
        <property name="acquireRetryAttempts" value="2"/>

    </bean>

<!--    sqlSessionFactory-->

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
<!--        绑定mybatis配置文件-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
    </bean>

<!--    配置dao接口扫描包,动态实现了Dao接口可以注入到Spring容器中-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--        注入sqlSessionFactory-->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!--        要扫描的dao包-->
        <property name="basePackage" value="com.lix.dao"/>
    </bean>

</beans>

6.spring整合service层

<?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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">

<!--    扫描service下的包-->
    <context:component-scan base-package="com.lix.service"/>

<!--    将我们所有的业务类,注入到spring,可以通过配置,或者注解实现-->
    <bean id="BookServiceImpl" class="com.lix.service.BookServiceImpl">
        <property name="bookMapper" ref="bookMapper"/>
    </bean>
<!--    声明式事务-->
    <bean id="transactionManager" 			class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--        注入数据源-->
        <property name="dataSource" ref="dataSource"/>
    </bean>

<!--    aop事务支持-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="*" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>
    <aop:config>
        <aop:pointcut id="txPointCut" expression="execution(* com.lix.dao.*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
    </aop:config>

</beans>

7.spring整合controller层

<?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:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">

<!--   注解驱动 -->
    <mvc:annotation-driven/>

<!--  静态资源过滤  -->
    <mvc:default-servlet-handler/>

<!--   扫描包 -->
    <context:component-scan base-package="com.lix.controller"/>

<!--    视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp/"/>
    </bean>


</beans>

------项目框架搭建完成-----

  1. 报错:

    Could not find resource org/mybatis/example/mybatis-config.xml
    
  • 解决:纯配置文件路径错误,检查路径即可

  • 报错:

    org.apache.ibatis.builder.BuilderException: Error parsing SQL Mapper Configuration. Cause: java.io.IOException: Could not find resource
    
    • 解决:在pom.xml中加入以下配置

      <build>
              <resources>
                  <resource>
                      <directory>src/main/resources</directory>
                      <includes>
                          <include>**/*.properties</include>
                          <include>**/*.xml</include>
                      </includes>
                      <filtering>true</filtering>
                  </resource>
                  <resource>
                      <directory>src/main/java</directory>
                      <includes>
                          <include>**/*.properties</include>
                          <include>**/*.xml</include>
                      </includes>
                      <filtering>true</filtering>
                  </resource>
              </resources>
          </build>
      
      1. log4j配置文件
#将等级为DEBUG的日志信息输出到console和file这两个目的地,console和file的定义在下面的代码
log4j.rootLogger=DEBUG,console,file

#控制台输出的相关设置
log4j.appender.console = org.apache.log4j.ConsoleAppender
log4j.appender.console.Target = System.out
log4j.appender.console.Threshold = Debug
log4j.appender.console.layout = org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern = [%c]-%m%n

#文件输出的相关设置
log4j.appender.file = org.apache.log4j.RollingFileAppender
log4j.appender.file.File = ./log/lix.log
log4j.appender.file.MaxFileSize = 10mb
log4j.appender.file.Threshold = DEBUG
log4j.appender.file.layout = org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern = [%p][%d{yy-mm-dd}][%c]%m%n

#日志输出级别
log4j.logger.org.mybatis = DEBUG
log4j.logger.java.sql = DEBUG
log4j.logger.java.sql.Statement = DEBUG
log4j.logger.java.sql.ResultSet = DEBUG
log4j.logger.java.sql.PreparedStatement = DEBUG


二.注解CRUD

package com.lix.dao;

import com.lix.pojo.User;
import org.apache.ibatis.annotations.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * program mybatis-01
 * @author lix
 */
public interface UserMapper {
    /**
     * getUsers
     * @return
     */
    @Select("select * from user")
    List<User> getUsers();

    /**
     *
     * getUserById
     * @param id
     * @param name
     * @return
     * 方法存在多个参数,
     */
    @Select("select * from user where id=#{id}")
    User getUserById(@Param("id") int id, @Param("name") String name);
    /**
     * addUser
     * @param map
     * @return
     */
    @Insert("insert into user(id,name,pwd) values(#{id},#{name},#{pwd})")
    int addUser(Map<String,Object> map);

    /**
     * updateUser
     * @param map
     * @return
     */
    @Update("update user set name = #{name},pwd=#{pwd} where id = #{id}")
    int updateUser(Map<String,Object> map);

    /**
     * deleteUse
     * @param id
     * @return
     */
    @Delete("delete from user where id = #{id}")
    int deleteUse(@Param("id") int id);


}

【注意:我们必须要把核心配置类(UserMapper.java)绑定到核心配置文件中(mybatis-config.xml)】

  1. 关于@Param()注解

    • 基本类型的参数或者String类型,需要加
    • 引用类型不需要加
    • 如果只有一个基本类型的话,可以忽略,建议加
    • 我们在SQL中引用的就是我们这里的的@Param()中设定的属性名
  2. {} 可以很大程度的防止sql注入 ${}

  3. Lombok

    • Project Lombok is a java library that automatically plugs into your editor and build tools, spicing up your java.
      Never write another getter or equals method again, with one annotation your class has a fully featured builder, Automate your logging variables, and much more.

      • Project Lombok是一个java库,它可以自动插入到你的编辑器和构建工具中,为您的java注入新的活力。

        不要再编写其他getter或equals方法,有了一个注释,类就有了功能齐全的构建器、自动化日志变量等等。

    • package com.lix.dao;
      
      import lombok.AllArgsConstructor;
      import lombok.Data;
      import lombok.NoArgsConstructor;
      
      /**
       * program mybatis-02
       * @author lix
       * description 加在类上所有属性都加,加在属性上,只有属性加
       */
      @Data
      @AllArgsConstructor
      @NoArgsConstructor
      public class User {
          private int id;
          private String name;
          private String pwd;
      
      }
      

4.1、按照查询嵌套处理

<select id="getStudent" resultMap="StudentTeacher">
    select * from student
</select>
<resultMap id="StudentTeacher" type="Student">
    <result column="id" property="id"/>
    <result column="name" property="name"/>
    <!--复杂属性单独处理
                对象:association
                集合:collection
            -->
    <association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
    <collection property=""/>
</resultMap>
<select id="getTeacher" resultType="Teacher">
    select * from teacher where id = #{tid};
</select>

三.动态SQL

<select id="iii" resultType="sss">
        select * from mybatis.user
        <where>
            <if test="title != null">
                title =1
            </if>
        </where>
        <set></set>
    </select>
posted @ 2021-08-16 17:55  六爻呈乾  阅读(53)  评论(0编辑  收藏  举报