前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >MyBatis入门

MyBatis入门

作者头像
CBeann
发布2023-12-25 16:15:39
1380
发布2023-12-25 16:15:39
举报
文章被收录于专栏:CBeann的博客CBeann的博客

项目总体结构

创建数据库,数据表

在项目中创建类

代码语言:javascript
复制
package entity;

public class Student {
	
	private int id;
	private Integer age;
	private Integer score;
	private String name;
	public Student() {		
	}
	public Student(String name,Integer age, Integer score) {
	
		this.age = age;
		this.score = score;
		this.name = name;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	public Integer getScore() {
		return score;
	}
	public void setScore(Integer score) {
		this.score = score;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	@Override
	public String toString() {
		return "Student [id=" + id + ", age=" + age + ", score=" + score
				+ ", name=" + name + "]";
	}
	

	

}

添加jar,mybatis.xml,db_mysql.properties

mybatis.xml

代码语言:javascript
复制
<?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_mysql.properties"></properties>

	<!-- 设置别名 -->
	<typeAliases>
		<package name="entity"></package>
	</typeAliases>

	<environments default="mysqlEM">

       <!--数据库连接信息,注意上面的default属性和下面的id属性一致 -->
		<environment id="mysqlEM">
			<transactionManager type="JDBC">
			</transactionManager>

			<dataSource type="POOLED">
				<property name="driver" value="${jdbc.driverClass}" />
				<property name="url" value="${jdbc.jdbcUrl}" />
				<property name="username" value="${jdbc.user}" />
				<property name="password" value="${jdbc.password}" />

			</dataSource>
		</environment>
	</environments>
   
   <!-- 引入类接口的xml -->
	<mappers>
		<mapper resource="StudentMapper.xml" />
	</mappers>


</configuration>

db_mysql.properties

代码语言:javascript
复制
jdbc.user=root
jdbc.password=root
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql://localhost:3306/text

jdbc.initPoolSize=5
jdbc.maxPoolSize=10
#...

lo4j.properties

代码语言:javascript
复制
log4j.rootLogger=DEBUG, Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%-5p   %m%n
log4j.logger.org.apache=INFO

创建操作类的接口

代码语言:javascript
复制
package dao;

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

import entity.Student;

public interface IStudentDao {
  
    //将查询对象封装到Student对象中,测试if动态拼接字符串
    List<Student>  selectStudentByIf(Student student);
    
    //测试Where动态拼接字符串
    List<Student>  selectStudentByWhere(Student student);
    
    //测试choose动态拼接字符串
    List<Student>  selectStudentByChoose(Student student);
    
    //测试传入是数组的foreach动态拼接字符串
    List<Student>  selectStudentByForeach(int[]  a);
    
    //测试传入是List的foreach动态拼接字符串
    List<Student>  selectStudentByForeach2(List  a);
    } 

创建对应4中接口的XML

代码语言:javascript
复制
<?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="dao.IStudentDao">

   <!-- 当表的字段和类的属性不一样时候
   column指向的是表中的字段,property指向的是类中的属性
    <resultMap type="entity.Student" id="StudentResult">
    <id column="tid"  property="id"/>
    <result column="tusername"  property="username"/>
    <result column="tpassword"   property="password"/>   
  </resultMap>
   -->


<select id="selectStudentByIf"  resultType="Student">
  select id,name,score from student where 1 = 1
  <if test="name != null and name != ''">
     and name like '%' #{name} '%'
  </if>
    <if test="age >0">
     and age > #{age}
  </if>
</select>


<select id="selectStudentByWhere"  resultType="Student">
  select id,name,score from student 
  <where>
     <if test="name != null and name != ''">
	   and name like '%' #{name} '%'
    </if>
	<if test="age >0">
		and age > #{age}
	</if>
  </where>
</select>
	
	
	
<select id="selectStudentByChoose"  resultType="Student">
  select id,name,score from student 
  <where>
     <choose>
        <when test=" name !=null and name !='' "> and name like '%' #{name} '%' </when>
         <when test =" age > 0"> and age > #{age}</when>
        <otherwise>and 1 = 2</otherwise>
     </choose>
  </where>
</select>




<select id="selectStudentByForeach"  resultType="Student">
  select id,name,age,score from student 
  <where>
     <if test="array.length > 0">
       id in
       <foreach collection="array"  open="("  close=")"  item="myid" separator=",">
         #{myid}
       </foreach>
     </if>
  </where>
</select>

<select id="selectStudentByForeach2"  resultType="Student">
  select id,name,age,score from student 
  <where>
     <if test="list.size > 0">
       id in
       <foreach collection="list"  open="("  close=")"  item="myid" separator=",">
         #{myid}
       </foreach>
     </if>
  </where>
</select>
</mapper>

测试

工具类,用于获取SqlSession

代码语言:javascript
复制
package until;

import java.io.IOException;
import java.io.Reader;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class MyBatisUntil {

	private static SqlSessionFactory sqlSessionFactory;

	public static SqlSession getSqlSession() {
		Reader reader;
		try {
			reader = Resources.getResourceAsReader("mybatis.xml");
			if (sqlSessionFactory == null) {

				sqlSessionFactory = new SqlSessionFactoryBuilder()
						.build(reader);
			}
			SqlSession sqlSession = sqlSessionFactory.openSession();

			return sqlSession;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return null;
	}

}

Main

代码语言:javascript
复制
package text;

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

import org.apache.ibatis.session.SqlSession;
import org.junit.Before;
import org.junit.Test;

import until.MyBatisUntil;
import dao.IStudentDao;
import entity.Student;

public class Main {
	
	private IStudentDao dao;
	@Before
	public void before(){
		SqlSession sqlSession=MyBatisUntil.getSqlSession();
		dao=sqlSession.getMapper(IStudentDao.class);
	}
	
	@Test
	public void selectStudentByForeach2(){
        
        List<Integer> a=new ArrayList<Integer>();
        a.add(1);
        a.add(3);
        List<Student> students=dao.selectStudentByForeach2(a);
        for (Student student : students) {
			System.out.println(student);
		}	
	}


}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-03-07,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 项目总体结构
  • 创建数据库,数据表
  • 在项目中创建类
  • 添加jar,mybatis.xml,db_mysql.properties
    • mybatis.xml
      • db_mysql.properties
        • lo4j.properties
        • 创建操作类的接口
        • 创建对应4中接口的XML
        • 测试
          • 工具类,用于获取SqlSession
            • Main
            相关产品与服务
            腾讯云服务器利旧
            云服务器(Cloud Virtual Machine,CVM)提供安全可靠的弹性计算服务。 您可以实时扩展或缩减计算资源,适应变化的业务需求,并只需按实际使用的资源计费。使用 CVM 可以极大降低您的软硬件采购成本,简化 IT 运维工作。
            领券
            问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档