Java教程

javaee 实现数据库查询操作mybatis

本文主要是介绍javaee 实现数据库查询操作mybatis,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

 

 

项目路径和数据库如上

1.pom.xml

<properties>
    <maven.compiler.source>8</maven.compiler.source>
    <maven.compiler.target>8</maven.compiler.target>
</properties>

<dependencies>
    <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.2</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.49</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/junit/junit -->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>
</dependencies>

2.db.properties
jdbc.driver = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/chapter03?useUnicode=true&characterEncoding=utf-8
jdbc.username = root
jdbc.password = 123

3.mybatis-config.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>
    <properties resource="db.properties"/>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC" />
            <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>
    <mappers>
        <package name="com.ssm.mybatis.dao"/>
    </mappers>
</configuration>

4.IStuClassMapper
package com.ssm.mybatis.dao;

import com.ssm.mybatis.pojo.StuClass;
import org.apache.ibatis.annotations.Many;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;

public interface IStuClassMapper {
    @Select("select * from stu_class where cid= #{cid}")
    @Results({ @Result(id = true, column = "cid", property = "cid"),
            @Result(column = "cname", property = "cname"),
            @Result(column = "sum", property = "sum"),
            @Result(column = "cid", property = "stuList",
                    many = @Many(
                            select = "com.ssm.mybatis.dao.IStudentMapper.selectStudentByCid"
                    )
            )
    })
    public StuClass selectStudentByClassId(int id);
}

5.IStudentMapper
package com.ssm.mybatis.dao;

import com.ssm.mybatis.pojo.Student;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

public interface IStudentMapper {
    @Select("select * from stu_info where sid= #{sid}")
    @Results({@Result(id = true, column = "sid", property = "sid"),
            @Result(column = "sname", property = "sname"),
            @Result(column = "age", property = "age"),
            @Result(column = "course", property = "course")})
    public Student selectStudentById(int id);

    @Update("update stu_info set sname = #{sname}, age = #{age} where sid = #{sid}")
    public int updateStudent(Student student);

    @Select("select * from stu_info where classid = #{cid}")
    public List<Student> selectStudentByCid(int cid);
}

6.StuClass
package com.ssm.mybatis.pojo;

import java.util.List;

public class StuClass {
    private int cid;
    private String cname;
    private int sum;
    private List<Student> stuList;

    public int getCid() {
        return cid;
    }

    public void setCid(int cid) {
        this.cid = cid;
    }

    public String getCname() {
        return cname;
    }

    public void setCname(String cname) {
        this.cname = cname;
    }

    public int getSum() {
        return sum;
    }

    public void setSum(int sum) {
        this.sum = sum;
    }

    public List<Student> getStuList() {
        return stuList;
    }

    public void setStuList(List<Student> stuList) {
        this.stuList = stuList;
    }

    @Override
    public String toString() {
        return "StuClass{" +
                "cid=" + cid +
                ", cname='" + cname + '\'' +
                ", sum=" + sum +
                ", stuList=" + stuList +
                '}';
    }
}

7.Student
package com.ssm.mybatis.pojo;

public class Student {
    private int sid;
    private String sname;
    private String age;
    private String course;

    public int getSid() {
        return sid;
    }

    public void setSid(int sid) {
        this.sid = sid;
    }

    public String getSname() {
        return sname;
    }

    public void setSname(String sname) {
        this.sname = sname;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

    public String getCourse() {
        return course;
    }

    public void setCourse(String course) {
        this.course = course;
    }

    @Override
    public String toString() {
        return "Student{" +
                "sid=" + sid +
                ", sname='" + sname + '\'' +
                ", age='" + age + '\'' +
                ", course='" + course + '\'' +
                '}';
    }
}

8.MyBatisUtils
package com.ssm.mybatis.utils;

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.Reader;

public class MyBatisUtils {
    private static SqlSessionFactory sqlSessionFactory = null;
    static {
        try {
            Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static SqlSession getSession()
    {
        return sqlSessionFactory.openSession();
    }
}

9.MyBatisTest
package test;

import com.ssm.mybatis.dao.IStuClassMapper;
import com.ssm.mybatis.dao.IStudentMapper;
import com.ssm.mybatis.pojo.StuClass;
import com.ssm.mybatis.pojo.Student;
import com.ssm.mybatis.utils.MyBatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;

public class MyBatisTest {
    @Test
    public void findStudentById(){
        SqlSession session = MyBatisUtils.getSession();
        IStudentMapper iStudentMapper = session.getMapper(IStudentMapper.class);
        Student student = iStudentMapper.selectStudentById(1);
        System.out.println(student.toString());
        session.close();
    }

    @Test
    public void findStudentByCid(){
        SqlSession session = MyBatisUtils.getSession();
        IStuClassMapper iStuClassMapper = session.getMapper(IStuClassMapper.class);
        StuClass stuClass = iStuClassMapper.selectStudentByClassId(1);
        List<Student> students = stuClass.getStuList();
        for(Student student : students){
            System.out.println(student.toString());
        }
        session.close();
    }

    @Test
    public void updateStudentById(){
        SqlSession session = MyBatisUtils.getSession();
        IStudentMapper iStudentMapper = session.getMapper(IStudentMapper.class);
        Student student = new Student();
        student.setSid(1);
        student.setSname("lihao");
        student.setAge("20");
        System.out.println(student);
        int cnt = iStudentMapper.updateStudent(student);
        if(cnt > 0){
            System.out.println("update successful!");
        }
        session.commit();
        session.close();
    }
}

 

 

 
 

 

 
 
 

 

       

 

 

这篇关于javaee 实现数据库查询操作mybatis的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!