mybaits基于注解的实现数据多表关联的查询

一.概述

mybaits基于注解的实现数据多表关联的查询

mybaits基于注解的实现数据多表关联的查询

mybaits基于注解的实现数据多表关联的查询

二.注解实现简单的crud操作

2.1 新建工程如下

mybaits基于注解的实现数据多表关联的查询

2.2 pom文件中依赖的配置

 <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.13</version>
      <scope>test</scope>
    </dependency>
    <!--mywql dueong  -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.32</version>
    </dependency>
    <!--mybaits -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.4.5</version>
    </dependency>
    <!-- log4j-->
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.17</version>
    </dependency>
    <!-- 分页插件-->
    <dependency>
      <groupId>com.github.pagehelper</groupId>
      <artifactId>pagehelper</artifactId>
      <version>3.7.5</version>
    </dependency>
    <dependency>
      <groupId>com.github.jsqlparser</groupId>
      <artifactId>jsqlparser</artifactId>
      <version>0.9.1</version>
    </dependency>

2.3 实体层

package com.ljf.mybaits.relation.annotation.domain;

import java.util.Date;

/**
 * @ClassName: User
 * @Description: TODO
 * @Author: liujianfu
 * @Date: 2021/02/18 20:02:38 
 * @Version: V1.0
 **/
public class User {
    private int id;
    private String userName;
    private Date birthday;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", userName='" + userName + '\'' +
                ", birthday=" + birthday +
                '}';
    }
}

2.4 dao层

package com.ljf.mybaits.relation.annotation.dao;
import com.ljf.mybaits.relation.annotation.domain.User;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.io.IOException;
import java.util.List;

public interface UserMapper {
    @Insert("insert into tb_users values(#{id},#{userName},#{birthday})")
    public void save(User user) throws IOException;
    @Update("update tb_users set user_name=#{userName} where id=#{id}")
    public void update(User user);
    @Delete("delete from tb_users where id=#{id}")
    public void delete(int id);
    @Select("select id,user_name userName,birthday from tb_users where id=#{id}")
    public User findById(int id);
    @Select("select id,user_name userName,birthday   from tb_users")
    public List<User> findAll();
}

2.5 service层

service接口

package com.ljf.mybaits.relation.annotation.service;

import com.ljf.mybaits.relation.annotation.domain.User;
import org.apache.ibatis.annotations.Select;

import java.io.IOException;
import java.util.List;

public interface UserService {
    public void save(User user) throws IOException;
    public void update(User user) throws IOException;
    public void delete(int id) throws IOException;
    public User findById(int id) throws IOException;
    public List<User> findAll() throws IOException;
}

service接口的实现层

package com.ljf.mybaits.relation.annotation.service.impl;

import com.ljf.mybaits.relation.annotation.dao.UserMapper;
import com.ljf.mybaits.relation.annotation.domain.User;
import com.ljf.mybaits.relation.annotation.service.UserService;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

/**
 * @ClassName: UserServiceImpl
 * @Description: TODO
 * @Author: liujianfu
 * @Date: 2021/02/18 20:17:17 
 * @Version: V1.0
 **/
public class UserServiceImpl implements UserService {
    private UserMapper mapper;
    @Override
    public void save(User user) throws IOException {
        InputStream resourceAsStream = Resources.getResourceAsStream("mybaitsConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        mapper = sqlSession.getMapper(UserMapper.class);
        mapper.save(user);
    }

    @Override
    public void update(User user) throws IOException {
        InputStream resourceAsStream = Resources.getResourceAsStream("mybaitsConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        mapper = sqlSession.getMapper(UserMapper.class);
        mapper.update(user);
    }

    @Override
    public void delete(int id) throws IOException {
        InputStream resourceAsStream = Resources.getResourceAsStream("mybaitsConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        mapper = sqlSession.getMapper(UserMapper.class);
        mapper.delete(id);
    }

    @Override
    public User findById(int id) throws IOException {
        InputStream resourceAsStream = Resources.getResourceAsStream("mybaitsConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        mapper = sqlSession.getMapper(UserMapper.class);
       User u= mapper.findById(id);
        return u;
    }

    @Override
    public List<User> findAll() throws IOException {
        InputStream resourceAsStream = Resources.getResourceAsStream("mybaitsConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        mapper = sqlSession.getMapper(UserMapper.class);
        List<User> userList=mapper.findAll();
        return userList;
    }
}

2.6 resource层

1.log4j的配置文件


######################
## set log levels
######################
log4j.rootLogger=DEBUG,info,CONSOLE,FILEOUT
#DEBUG,CONSOLE,FILE,ROLLING_FILE,MAIL,DATABASE
log4j.addivity.org.apache=true
######################
## CONSOLE Appender ##
######################
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.Threshold=DEBUG
log4j.appender.CONSOLE.Target=System.out
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=[%-5p][%d{yyyy-MM-dd HH\:mm\:ss,SSS}][%c] \:%m%n
#log4j.appender.CONSOLE.layout.ConversionPattern=[framework] %d - %c -%-4r [%t] %-5p %c %x - %m%n\u00A0
#log4j.appender.CONSOLE.layout.ConversionPattern=[start]%d{DATE}[DATE]%n%p[PRIORITY]%n%x[NDC]%n%t[THREAD] n%c[CATEGORY]%n%m[MESSAGE]%n%n
######################
## Rolling File Appender
######################
log4j.appender.FILEOUT=org.apache.log4j.RollingFileAppender
log4j.appender.FILEOUT.File=E:/logs/allError.log
#log4j.appender.FILEOUT.Threshold=ALL
log4j.appender.FILEOUT.Threshold=INFO
log4j.appender.FILEOUT.Append=true
log4j.appender.fileout.MaxFileSize=1000KB
#log4j.appender.ROLLING_FILE.MaxBackupIndex=1
log4j.appender.FILEOUT.layout=org.apache.log4j.PatternLayout
log4j.appender.FILEOUT.layout.ConversionPattern=[%-5p][%d{yyyy-MM-dd HH\:mm\:ss,SSS}][%c] \:%m%n
#log4j.appender.CONSOLE.layout.ConversionPattern=[framework] %d - %c -%-4r [%t] %-5p %c %x - %m%n\u00A0
#######################
#info log
log4j.logger.info=info
log4j.appender.info=org.apache.log4j.DailyRollingFileAppender 
log4j.appender.info.DatePattern='_'yyyy-MM-dd'.log'
log4j.appender.info.File=d:/info.log
log4j.appender.info.Append=true
log4j.appender.info.Threshold=INFO
log4j.appender.info.layout=org.apache.log4j.PatternLayout 
log4j.appender.info.layout.ConversionPattern=[%-5p][%d{yyyy-MM-dd HH\:mm\:ss,SSS}][%c] \:%m%n
### File Appender
#######################
#log4j.appender.FILE=org.apache.log4j.FileAppender
#log4j.appender.FILE.File=E:/logs/all.log
#log4j.appender.FILE.Append=true
#log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
#log4j.appender.CONSOLE.layout.ConversionPattern=[%-5p][%d{yyyy-MM-dd HH\:mm\:ss,SSS}][%c] \:%m%n
##log4j.appender.CONSOLE.layout.ConversionPattern=[framework] %d - %c -%-4r [%t] %-5p %c %x - %m%n\u00A0
#####################
## Socket Appender
#####################
#log4j.appender.SOCKET=org.apache.log4j.RollingFileAppender
#log4j.appender.SOCKET.RemoteHost=localhost
#log4j.appender.SOCKET.Port=5001
#log4j.appender.SOCKET.LocationInfo=true
## Set up for Log Facter 5
#log4j.appender.SOCKET.layout=org.apache.log4j.PatternLayout
#log4j.appender.SOCET.layout.ConversionPattern=[start]%d{DATE}[DATE]%n%p[PRIORITY]%n%x[NDC]%n%t[THREAD]%n%c[CATEGORY]%n%m[MESSAGE]%n%n
#########################
## Log Factor 5 Appender
#########################
#log4j.appender.LF5_APPENDER=org.apache.log4j.lf5.LF5Appender
#log4j.appender.LF5_APPENDER.MaxNumberOfRecords=2000
########################
## SMTP Appender
########################
#log4j.appender.MAIL=org.apache.log4j.net.SMTPAppender
#log4j.appender.MAIL.Threshold=FATAL
#log4j.appender.MAIL.BufferSize=10
#log4j.appender.MAIL.From=openwolfl@163.com
#log4j.appender.MAIL.SMTPHost=mail.openwolf.com
#log4j.appender.MAIL.Subject=Log4J Message
#log4j.appender.MAIL.To=openwolfl@163.com
#log4j.appender.MAIL.layout=org.apache.log4j.PatternLayout
#log4j.appender.MAIL.layout.ConversionPattern=[framework] %d - %c -%-4r [%t] %-5p %c %x - %m%n
#########################
## JDBC Appender
########################
#log4j.appender.DATABASE=org.apache.log4j.jdbc.JDBCAppender
#log4j.appender.DATABASE.URL=jdbc:mysql://localhost:3306/test
#log4j.appender.DATABASE.driver=com.mysql.jdbc.Driver
#log4j.appender.DATABASE.user=root
#log4j.appender.DATABASE.password=root
#log4j.appender.DATABASE.sql=INSERT INTO LOG4J (Message) VALUES ('[framework] %d - %c -%-4r [%t] %-5p %c %x - %m%n')
#log4j.appender.DATABASE.layout=org.apache.log4j.PatternLayout
#log4j.appender.DATABASE.layout.ConversionPattern=[framework] %d - %c -%-4r [%t] %-5p %c %x - %m%n
#log4j.appender.A1=org.apache.log4j.DailyRollingFileAppender
#log4j.appender.A1.File=SampleMessages.log4j
#log4j.appender.A1.DatePattern=yyyyMMdd-HH'.log4j'
#log4j.appender.A1.layout=org.apache.log4j.xml.XMLLayout
####################
### myself Appender
####################
#log4j.appender.im = net.cybercorlin.util.logger.appender.IMAppender
#log4j.appender.im.host = mail.cybercorlin.net
#log4j.appender.im.username = username
#log4j.appender.im.password = password
#log4j.appender.im.recipient = corlin@yeqiangwei.com
#log4j.appender.im.layout=org.apache.log4j.PatternLayout
#log4j.appender.im.layout.ConversionPattern =[framework] %d - %c -%-4r [%t] %-5p %c %x - %m%n

2.mybaits-jdbc的配置文件

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/nongda
jdbc.username=root
jdbc.password=

3.mybaitsconfig的配置文件

<?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>
<properties resource="mybaits-jdbc.properties"></properties>
    <!-- 起别名-->
    <typeAliases>
        <typeAlias type="com.ljf.mybaits.relation.annotation.domain.User" alias="user"></typeAlias>
    </typeAliases>
    <!-- 注册类型注册器
    <typeHandlers>
        <typeHandler handler="com.mybaits.demo.handler.DataTypeTransfer"></typeHandler>
    </typeHandlers>
    -->
    <!--配置分页插件 -->
    <plugins>
        <plugin interceptor="com.github.pagehelper.PageHelper">
            <property name="dialect" value="mysql"/>
        </plugin>
    </plugins>
<!-- 数据源环境 -->
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>
 <!-- xxxmapper.xml都要在mybaits.config.xml文件中注册-->

    <!--加载映射关系-->
    <mappers>
        <!--指定接口所在的包-->
        <package name="com.ljf.mybaits.relation.annotation.dao"></package>
    </mappers>
</configuration>

mybaits基于注解的实现数据多表关联的查询

2.7 调用

package com.ljf.mybaits.relation.annotation;

import com.ljf.mybaits.relation.annotation.domain.User;
import com.ljf.mybaits.relation.annotation.service.UserService;
import com.ljf.mybaits.relation.annotation.service.impl.UserServiceImpl;

import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * Hello world!
 *
 */
public class App 
{
    public static void main( String[] args ) throws IOException {
        //add();
      //  update();
        findAll();
        findSingleUser();
        delete();
        findSingleUser();
        System.out.println( "Hello World!" );
    }
    /**
    * @author liujianfu
    * @description    添加
    * @date 2021/2/18 20:45
    * @param []
    * @return void
    */
    public static  void add() throws IOException {
        UserService us=new UserServiceImpl();
        User user = new User();
        user.setUserName("beijing");
        user.setId(23);
        user.setBirthday(new Date());
        us.save(user);
    }
    //修改
    public static void update() throws IOException {
        UserService us=new UserServiceImpl();
        User user = new User();
        user.setId(73);
         user.setUserName("tianjin");
        us.update(user);
    }
    //查询
    public static void findAll() throws IOException {
        UserService us=new UserServiceImpl();
       List<User> userList= us.findAll();
       for(User u:userList){
           System.out.println("u:"+u);
       }
    }
    //单个查询
    public static void findSingleUser() throws IOException {
        UserService us=new UserServiceImpl();
         User u= us.findById(23);
         System.out.println("u:"+u);
    }
    //删除
    public static  void delete() throws IOException {
        UserService us=new UserServiceImpl();
         us.delete(23);
    }
}

 

上一篇:中华古诗词知识图谱之网页设计及实现(完结)


下一篇:SSM整合