myBatis01
无聊搞一下myBatis
1.新建properties属性文件 内容如下:
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/db_mybatis
jdbc.username=root
jdbc.password=1234
2.新建mybatis-config.xml文件 内容如下:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
<configuration>
<properties resource="jdbc.properties"/>
<typeAliases>
<typeAlias alias="Student" type="com.java1234.model.Student"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/java1234/mappers/StudentMapper.xml" />
</mappers>
</configuration>
3.导入mysqljdbc驱动和mybatis jar包文件
4.新建pojo即普通的java类Student 代码略过,一堆getset,注意定义构造方法
5.新建sqlSessionFactoryUtil类,注意该类中是静态方法,和hibernate相似 代码如下:
< /mapper>
package com.java1234.util;
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;
public class SqlSessionFactoryUtil {
private static SqlSessionFactory SqlSessionFatory;
public static SqlSessionFactory getSqlSessionFactory(){
if(SqlSessionFatory==null){
InputStream inputStream=null;
try{
inputStream=Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFatory=new SqlSessionFactoryBuilder().build(inputStream);
}catch(Exception e){
e.printStackTrace();
}
}
return SqlSessionFatory;
}
public static SqlSession openSession(){
return getSqlSessionFactory().openSession();
}
}
6.新建mapper接口和mapper映射文件 代码如下:
package com.java1234.mappers;
import com.java1234.model.Student;
public interface StudentMapper {
public int add(Student student);
}
=======
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<mapper namespace="com.java1234.mappers.StudentMapper">
<insert id="add" parameterType="Student" >
insert into t_student values(null,#{name},#{age})
</insert>
7.最后测试 代码如下
package com.java1234.service;
import org.apache.ibatis.session.SqlSession;
import com.java1234.mappers.StudentMapper;
import com.java1234.model.Student;
import com.java1234.util.SqlSessionFactoryUtil;
public class StudentTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
SqlSession sqlSession=SqlSessionFactoryUtil.openSession();
StudentMapper studentMapper= sqlSession.getMapper(StudentMapper.class);
Student student=new Student("梁方明",30);
int result= studentMapper.add(student);
sqlSession.commit();
if(result>0){
System.out.println("添加成功");
}
}
}
8.这样就向mysql数据库添加了一条记录。