ibatis_note_1

本文介绍了一个简单的MyBatis入门示例,包括配置环境、创建User类、编写SqlMapConfig.xml配置文件、User.xml映射文件及查询操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

作为新手还是先照着做个小例子

一.导入ibatis包和mysql的jdbc包。

二.新建一个User类,包含id,name,sex。

三.写ibatis配置文件,SqlMapConfig.xml。

四.写sql映射的xml文件User.xml。

五.初始化配置文件并查询。

User.java

package com.forrest.ibatis.test.domain;

import java.io.Serializable;

public class User implements Serializable
{
	private Integer id;
	
	private String name;
	
	private Integer sex;

	public Integer getId()
	{
		return id;
	}

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

	public String getName()
	{
		return name;
	}

	public void setName(String name)
	{
		this.name = name;
	}

	public Integer getSex()
	{
		return sex;
	}

	public void setSex(Integer sex)
	{
		this.sex = sex;
	}
	
	
}

 

 SqlMapConfig.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>  
        <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://localhost:3306/ibatis1"/>   
                   <property name="username" value="java"/>
                   <property name="password" value="java"/>    
               </dataSource>   
           </environment>   
       </environments>   
       <mappers>   
           <mapper resource="com/forrest/ibatis/test/User.xml"/>   
       </mappers>  
  </configuration>  

 User.xml

<?xml version="1.0" encoding="UTF-8" ?>  
<!DOCTYPE mapper  
PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"  
"http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">  
  
<mapper namespace="UserMapper">  
    <select id="selectOne" parameterType="java.lang.Integer" resultType="com.forrest.ibatis.test.domain.User">  
        select * from t_user where id = #{id}
    </select>  
</mapper>

 main方法

public static void main(String[] args) throws IOException
	{
		String resource = "com/forrest/ibatis/test/SqlMapConfig.xml";
		Reader reader;
		reader = Resources.getResourceAsReader(resource);
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
		SqlSession sqlSession = sqlSessionFactory.openSession();
		User user = (User)sqlSession.selectOne("UserMapper.selectOne", "1");
		System.out.println(user.getId());
		System.out.println(user.getName());
		System.out.println(user.getSex());
	}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值