MyBatis_3 - MyBatis第一个Demo

废话不多说,直接上第一个MyBatis Demo

代码我上传了,下载下来,构建好数据库,可以直接运行...

MyBatis_Demo_1


数据库结构


数据库数据



项目工程结构



log4j.properties

log4j.rootLogger=DEBUG,CONSOLE,ARKSERVICES
log4j.addivity.org.apache=true
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.Threshold=DEBUG
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d %p %l - %m%n

log4j.appender.ARKSERVICES=org.apache.log4j.DailyRollingFileAppender
log4j.appender.ARKSERVICES.DatePattern='.'yyyy-MM-dd
log4j.appender.ARKSERVICES.File=./mybatis.log
log4j.appender.ARKSERVICES.Threshold=debug
log4j.appender.ARKSERVICES.layout=org.apache.log4j.PatternLayout
log4j.appender.ARKSERVICES.layout.ConversionPattern=%d %p - %m%n

jdbc.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test
jdbc.username=root
jdbc.password=123456


POJO对象/Student.java

package com.mybatis.bean;

/**
 * Created by CYX on 2017/3/25.
 */
public class Student {
	private int studentId;
	private String studentName;
	private int studentAge;
	private String studentPhone;
	public Student() {
	}
	public Student(int studentId, String studentName, int studentAge, String studentPhone) {
		this.studentId = studentId;
		this.studentName = studentName;
		this.studentAge = studentAge;
		this.studentPhone = studentPhone;
	}
	@Override
	public String toString() {
		return "Student{" +
				"studentId=" + studentId +
				", studentName='" + studentName + '\'' +
				", studentAge=" + studentAge +
				", studentPhone='" + studentPhone + '\'' +
				'}';
	}
	public int getStudentId() {
		return studentId;
	}
	public void setStudentId(int studentId) {
		this.studentId = studentId;
	}
	public String getStudentName() {
		return studentName;
	}
	public void setStudentName(String studentName) {
		this.studentName = studentName;
	}
	public int getStudentAge() {
		return studentAge;
	}
	public void setStudentAge(int studentAge) {
		this.studentAge = studentAge;
	}
	public String getStudentPhone() {
		return studentPhone;
	}
	public void setStudentPhone(String studentPhone) {
		this.studentPhone = studentPhone;
	}
}

映射器接口/StudentMapper.java

package com.mybatis.mapper;
import com.mybatis.bean.Student;
/**
 * Created by CYX on 2017/3/25.
 */
public interface StudentMapper {
	public Student getStudent(Long id);
	public int deleteStudent(Long id);
	public int insertStudent(Student student);
}


映射器XML/StudentMapper.xml

<?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="com.mybatis.mapper.StudentMapper">

	<!-- 查询一个对象 -->
	<select id="getStudent" resultType="student" parameterType="long">
		SELECT studentId,studentName,studentAge,studentPhone FROM student where studentId = #{id}
	</select>

	<!-- 插入一个对象 -->
	<insert id="insertStudent" parameterType="student">
		INSERT INTO student(studentName,studentAge,studentPhone)
		values (#{studentName},#{studentAge},#{studentPhone})
	</insert>

	<!-- 删除一个对象 -->
	<delete id="deleteStudent" parameterType="long">
		DELETE from student WHERE studentId = #{studentId}
	</delete>

</mapper>

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="jdbc.properties" />
		<!-- 自定义别名,类型命名,类别名 -->
		<typeAliases>
				<typeAlias alias="student" type="com.mybatis.bean.Student" />
		</typeAliases>

		<!-- 定义数据库信息,默认使用development数据库构建环境 -->
		<environments default="development">
				<environment id="development">
						<!-- 事务管理器 / 采用jdbc事务管理 -->
						<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>

		<!-- 定义映射器/sql语句的配置文件 -->
		<mappers>
				<mapper resource="com\mybatis\mapper\StudentMapper.xml" />
		</mappers>

</configuration>

SqlSessionFactoryUtil.java

package com.mybatis.utils;

import java.io.IOException;
import java.io.InputStream;

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 org.apache.log4j.Logger;

public class SqlSessionFactoryUtil {

		private static final Logger logger = Logger.getLogger(SqlSessionFactoryUtil.class);

		// SqlSessionFactory对象
		private static SqlSessionFactory sqlSessionFactory = null;
		// 类线程锁.
		private static final Class CLASS_LOCK = SqlSessionFactoryUtil.class;

		// 私有化构造器
		public SqlSessionFactoryUtil() {
		}

		/**
		 * 构建SqlSessionFactory
		 *
		 * @return
		 */
		private static SqlSessionFactory initSqlSessionFactory() {
				String resource = "mybatis_Config.xml";
				InputStream inputStream = null;

		try {
				inputStream = Resources.getResourceAsStream(resource);
		} catch (IOException e) {
				logger.error(e.getMessage(), e);
		}

		synchronized (CLASS_LOCK) {
				if (sqlSessionFactory == null) {
						sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
				}
		}

		return sqlSessionFactory;
		}

		/**
		 * 打开SqlSession
		 *
		 * @return
		 */
		public static SqlSession openSqlSession() {
				if (sqlSessionFactory == null) {
						initSqlSessionFactory();
				}
				return sqlSessionFactory.openSession();
		}

}

MyBatisServer.java

package com.mybatis.server;

import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

import com.mybatis.bean.Student;
import com.mybatis.mapper.StudentMapper;
import com.mybatis.utils.SqlSessionFactoryUtil;

/**
 * Created by CYX on 2017/3/25.
 */
public class MyBatisServer {

		private static final Logger logger = Logger.getLogger(MyBatisServer.class);

		public static void main(String[] args) {

		SqlSession sqlSession = null;

		try {

		PropertyConfigurator.configure("./conf/log4j.properties");

		sqlSession = SqlSessionFactoryUtil.openSqlSession();

		StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);

		Student student = new Student();
		student.setStudentName("JY");
		student.setStudentAge(24);
		student.setStudentPhone("66666");

//			int result = studentMapper.insertStudent(student);
//			logger.debug("insert result : " + result);

		 Student studentInfo = studentMapper.getStudent(4L);
		 logger.debug("student info : " + studentInfo.toString());

//			 int deleteResult = studentMapper.deleteStudent(7L);
//			 logger.debug("delete student : " + deleteResult);

		sqlSession.commit();
		} catch (Exception e) {
				logger.error(e.getMessage(), e);
				sqlSession.rollback();
		} finally {
				try {
						sqlSession.close();
				} catch (Exception e) {
						e.printStackTrace();
				}
		}

		}

}

这里我们的测试从数据库中根据ID,查询一个学生信息



这里说下,如果喜欢使用jdbc.properties配置文件传数据库参数的话,可以将配置信息,写在mybatis_Config.xml中即可。。。
比如像下面这样子
不过注意:'<properties resource="jdbc.properties" />'已经被我注释掉了。。。

<?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="jdbc.properties" /> -->
		<!-- 自定义别名,类型命名,类别名 -->
		<typeAliases>
				<typeAlias alias="student" type="com.mybatis.bean.Student" />
		</typeAliases>


		<!-- 定义数据库信息,默认使用development数据库构建环境 -->
		<environments default="development">
				<environment id="development">
						<!-- 事务管理器 / 采用jdbc事务管理 -->
						<transactionManager type="JDBC" />
						<!-- 配置数据库连接信息 -->
						<dataSource type="POOLED">
								<property name="driver" value="com.mysql.jdbc.Driver" />
								<property name="url" value="jdbc:mysql://localhost:3306/test" />
								<property name="username" value="root" />
								<property name="password" value="123456" />
						</dataSource>
				</environment>
		</environments>

		<!-- 定义映射器/sql语句的配置文件 -->
		<mappers>
				<mapper resource="com\mybatis\mapper\StudentMapper.xml" />
		</mappers>

</configuration>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值