首页 > 其他分享 >mybatis学习笔记

mybatis学习笔记

时间:2023-03-29 10:44:47浏览次数:42  
标签:int gender age 笔记 public 学习 sqlSession mybatis id

1、第一个mybatis

导入依赖

//mysql依赖
<dependency> <groupId>com.mysql</groupId> <artifactId>mysql-connector-j</artifactId> <version>8.0.31</version> </dependency>
//mybatis依赖
<dependency>
  <groupId>org.mybatis</groupId>
  <artifactId>mybatis</artifactId>
  <version>3.5.11</version>
</dependency>

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/db_stu?useSSL=true&useUnicode=true&characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
<!--映射xml,可映射多个文件--> <mappers> <mapper resource="com/xx/dao/userMapper.xml"/> </mappers> </configuration>

 

创建工具类

 private static SqlSessionFactory sqlSessionFactory;
    static {
        try {
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    public static SqlSession getSqlSession()
    {
         return  sqlSessionFactory.openSession();
    }

创建实体类

private int id;
    private String StudentName;
    private String gender;
    private int age;

    public Student() {
    }

    public Student(int id, String studentName, String gender, int age) {
        this.id = id;
        StudentName = studentName;
        this.gender = gender;
        this.age = age;
    }

    public int getId() {
        return id;
    }

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

    public String getStudentName() {
        return StudentName;
    }

    public void setStudentName(String studentName) {
        StudentName = studentName;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public int getAge() {
        return age;
    }

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

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", StudentName='" + StudentName + '\'' +
                ", gender='" + gender + '\'' +
                ", age=" + age +
                '}';
    }

创建接口

package com.xx.dao;
import com.xx.pojo.Student;
import java.util.List;

public interface studentMapper {
//查询全部学生
List<Student> getAllStudents();
//根据学号查找学生
Student getStudentById(int id);
//添加学生
int addStudent(Student stu);
//修改信息
int updateStudent(Student stu);
//删除学生信息
int deleteStudent(int id);
}

实现

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.xx.dao.studentMapper">
<select id="getAllStudents" resultType="com.xx.pojo.Student" >
select * from db_stu.student
</select>
<select id="getStudentById" resultType="com.xx.pojo.Student" parameterType="int">
select * from db_stu.student where id =#{id}
</select>
<insert id="addStudent" parameterType="com.xx.pojo.Student">
insert into db_stu.student(id,StudentName,gender,age) values(#{id},#{StudentName},#{gender},#{age})
</insert>
<update id="updateStudent" parameterType="com.xx.pojo.Student">
update db_stu.student set StudentName=#{StudentName},gender=#{gender},age=#{age} where id=#{id};
</update>
<delete id="deleteStudent" parameterType="int">
delete from db_stu.student where id =#{id};
</delete>
</mapper>

测试实例

@Test
public void addStudent()
{
SqlSession sqlSession=mybatisUtil.getSqlSession();
studentMapper stuMapper=sqlSession.getMapper(studentMapper.class);
int res= stuMapper.addStudent(new Student(6,"无敌战胜","神",999));
if(res>0)
{
System.out.println("插入成功");
sqlSession.commit();
}
sqlSession.close();
}
@Test
public void queryAllStudents()
{
SqlSession sqlSession=mybatisUtil.getSqlSession();
studentMapper stuMapper=sqlSession.getMapper(studentMapper.class);
List<Student> students=stuMapper.getAllStudents();
for (Student student : students) {
System.out.println(student);
}
sqlSession.close();
}
@Test
public void queryStudent()
{
SqlSession sqlSession=mybatisUtil.getSqlSession();
studentMapper stuMapper=sqlSession.getMapper(studentMapper.class);
Student stu=stuMapper.getStudentById(2);
System.out.println(stu);
sqlSession.close();
}
@Test
public void updateStudnet()
{
SqlSession sqlSession=mybatisUtil.getSqlSession();
studentMapper mapper = sqlSession.getMapper(studentMapper.class);
int res=mapper.updateStudent(new Student(6,"xxxiaoxing","男",19));
if(res>0)
{
System.out.println("修改成功");
sqlSession.commit();
}
sqlSession.close();
}
@Test
public void deleteStudent()
{
SqlSession sqlSession=mybatisUtil.getSqlSession();
studentMapper mapper = sqlSession.getMapper(studentMapper.class);
int res=mapper.deleteStudent(6);
if(res>0)
{
System.out.println("删除成功");
sqlSession.commit();
}
sqlSession.close();
}

注意:增删改需提交事务(SqlSession.commit())//否则操作无效

maven资源过滤问题 

在pom.xml添加

<!--在build中配置resources,来防止我们资源导出失败的问题-->
<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>

 

标签:int,gender,age,笔记,public,学习,sqlSession,mybatis,id
From: https://www.cnblogs.com/xxxiaoxing/p/17263125.html

相关文章

  • Mybatis-Plus自定义TypeHandler映射JSON类型为List
    1.实体类注意点:别忘了autoResultMap=true@Data@TableName(value="report",autoResultMap=true)publicclassReportimplementsSerializable{privates......
  • python代码-基于深度强化学习的微能源网能量管理与优化策略研究
    python代码-基于深度强化学习的微能源网能量管理与优化策略研究关键词:微能源网;能量管理;深度强化学习;Q-learning;DQN内容::面向多种可再生能源接入的微能源网,提出一种基于深......
  • 苹果吐槽:平板和笔记本合体如同烤箱和冰箱杂交
    “你可以将烤箱和冰箱合二为一,但是这很有可能会引起消费者的反感。”苹果CEO库克在财务报告会上开门见山对笔记本和平板的合体发表吐槽。由于Windows8操作系统对于不同的设......
  • 在mybatis的xml文件中如何使用test标签
    1.等于条件的两种写法①将双引号和单引号的位置互换<!--test标签用来条件判断,为true则执行标签下的sql--><iftest='testString!=nullandtestString=="A"'>......
  • 狂神说MyBatis01:第一个程序
    1.简介1.1什么是MyBatisMyBatis是一款优秀的持久层框架MyBatis避免了几乎所有的JDBC代码和手动设置参数以及获取结果集的过程MyBatis可以使用简单的XML或注解......
  • Spring整合Mybatis遇到的问题(一)
    问题1问题原因:在数据源配置类中没有创建事务管理在数据源配置类中添加好事务管理器的Bean即可问题2其实出现这个问题实质就是mapper接口和mapper.xml文件没有映射起......
  • 学习C语言第二天
    关于昨天的流程控制,决定暂时跳过,偷懒一下,因为再学习java对这些流程控制语句较为熟悉,故明天或者后天再做一些习题进行补充,今天进行数组的学习。一.数组1.引入当......
  • 机器学习建模中--先“特征选择”还是先“划分数据集”?
    应该先进行“特征选择”,再“划分数据集”。这样可以避免数据泄露。测试集就应该当做“看不见的数据”,只能在最后用一次,按照这个原则处理。代码实例:#-*-coding:utf-8......
  • trading view 学习
    中文开发文档网站:https://zlq4863947.gitbook.io/tradingview/参考:https://github.com/zlq4863947/tradingViewWikiCn参考:https://cn.tradingview.com/lightweight-cha......
  • Effective C++笔记
    EffectiveC++ThirdEdition改善程序与设计的55个具体做法导读除非有理由允许构造函数被用于隐式类型转换,否则‘我’会把它声明为explicit(阻止隐式类型转换)classtmp{......