初始Mybatis做java项目

1、创建一个Maven JAVA工程exp

2、在mysql数据库中创建表;

DROP TABLE IF EXISTS exp_stu;
CREATE TABLE exp_stu(
    stuno int,
    name  varchar(20),
    sex   varchar(20),
    score int
);

3、在pom.xml中配置

<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
	<dependency>
	    <groupId>org.mybatis</groupId>
	    <artifactId>mybatis</artifactId>
	    <version>3.4.6</version>
	</dependency>
	<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
	<dependency>
	    <groupId>mysql</groupId>
	    <artifactId>mysql-connector-java</artifactId>
	    <version>5.1.48</version>
	</dependency>

4、配置mybatis-config.xml

特别注意:

<property name="url" value="jdbc:mysql://127.0.0.1:3306/stu_info?useUnicode=true&amp;characterEncoding=utf-8&amp;useSSL=FALSE&amp;serverTimezone=UTC"/>      这里的stu_info是你要连接的数据库的表名

<property name="username" value="##"/>   value  这里填自己的数据库名
<property name="password" value="##"/>    value  这里填自己的数据库密码

<?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>   
    <settings>   
        <!-- changes from the defaults for testing -->   
        <setting name="cacheEnabled" value="false" />   
        <setting name="useGeneratedKeys" value="true" />   
        <setting name="defaultExecutorType" value="REUSE" />   
    </settings>   
    <environments default="development">
       <environment id="development">   
           <transactionManager type="jdbc"/>
           <dataSource type="POOLED">   
              <property name="driver" value="com.mysql.jdbc.Driver"/>
              <property name="url" value="jdbc:mysql://127.0.0.1:3306/stu_info?useUnicode=true&amp;characterEncoding=utf-8&amp;useSSL=FALSE&amp;serverTimezone=UTC"/>   
              <property name="username" value=""/>
              <property name="password" value=""/>
           </dataSource>
       </environment>
    </environments> 
    <mappers>
        <mapper class="demo.exp4_mybatis.StudentMapper" />
    </mappers>   
</configuration>  

 

5、实现MyBatisUtil.java

package demo.exp4_mybatis;
import java.io.IOException;
import java.io.Reader;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class MyBatisUtil {
	private final static SqlSessionFactory sqlSessionFactory;
	static {
		String resource = "mybatis-config.xml";
		Reader reader = null;
		try {
			reader = Resources.getResourceAsReader(resource);
		} catch (IOException e) {
			System.out.println(e.getMessage());
		}
		sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
	}

	public static SqlSessionFactory getSqlSessionFactory() {
		return sqlSessionFactory;
	}
}

6、写接口StudentMapper.java,用注解方式完成向exp_stu表的插入操作和查询操作

ps:StudentMapper是一个接口,它的实现就是上面的注解形式,即SQL语句

package demo.exp4_mybatis;

import java.util.Map;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

public interface StudentMapper {

//用注解方式完成向exp_stu表的插入操作和查询操作;
	@Insert("inert into exp_stu values(#{stuno},#{name},#{sex},#{score})")
	public void insertStu(@Param("stuno")Integer stuno,@Param("name")String name,@Param("sex")String sex,@Param("score")Integer score);
	
	@Select("select*from exp_stu where stuno=#{stuno}")
	public Map<Object, Object> getStu(int stuno);
}

7、在主程序中实现向数据库中插入一条记录(1001, zhangshan, male, 95),并查询1001,在屏幕上打印输出姓名和成绩

package demo.exp4_mybatis;

import java.util.Map;

import org.apache.ibatis.session.SqlSession;

/**
 * Hello world!
 *
 */
public class Test 
{
	public static void insertStu(Integer stuno, String name, String sex, Integer score) {
		// TODO Auto-generated method stub
		SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession();
		
		try {
			StudentMapper studentMapper=sqlSession.getMapper(StudentMapper.class);
			studentMapper.insertStu(stuno, name, sex, score);
			sqlSession.commit();
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			sqlSession.close();
		}
	}
	
	public static void getStu(int stuno) {
		// TODO Auto-generated method stub
		SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession();
		
		try {
			StudentMapper studentMapper=sqlSession.getMapper(StudentMapper.class);
			Map<Object, Object> student =studentMapper.getStu(stuno);
			System.out.println("name:"+student.get("name"));
			System.out.println("sex:"+student.get("sex"));
			System.out.println("score:"+(Object)(student.get("score")));
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		sqlSession.close();
		
	}
	
    public static void main( String[] args )
    {
    	
//    	在主程序中实现向数据库中插入一条记录(1001, zhangshan, male, 95),
//    	并查询1001,在屏幕上打印输出姓名和成绩
    	insertStu(1001,"zhangsan","male",95);
    	getStu(1001);
    	
        
    }
}

常见问题:

1、

mybatis-config.xml放置的位置,和java程序在同一包下。

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

念衢

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值