MyBatis01(测试连接数据库add)

目录结构:

MyBatis01(测试连接数据库add)_第1张图片

引入jdbc和mybatis的jar

 

1.创建mybatis的工具类SqlSessionFactoryUtil:

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 sqlSessionFactory;

public static SqlSessionFactory getSqlSessionFactory(){
if(sqlSessionFactory==null){
InputStream inputStream=null;
try{
inputStream=Resources.getResourceAsStream("mybatis-config.xml");
sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
}catch(Exception e){
e.printStackTrace();
}
}
return sqlSessionFactory;
}

public static SqlSession openSession(){
return getSqlSessionFactory().openSession();
}
}

 

2.配置mybatis-config.xml:























 

3.配置jdbc.properties:

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/db_mybatis?characterEncoding=utf8
jdbc.username=root
jdbc.password=123456

 

4.创建实体类Student:

public class Student {
private Integer id;
private String name;
private Integer age;

public Student() {
super();
// TODO Auto-generated constructor stub
}

public Student(String name, Integer age) {
super();
this.name = name;
this.age = age;
}

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 getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
} 


}

 

5.创建实体类对应的mapper和mapper对应的xml文件:

 

StudentMapper:

import com.model.Student;

public interface StudentMapper {
public int add(Student student);

}

 

StudentMapper.xml:





insert into t_student values(null,#{name},#{age})

 

 

最后编写测试类:

import org.apache.ibatis.session.SqlSession;


import com.mappers.StudentMapper;
import com.model.Student;
import com.util.SqlSessionFactoryUtil;

public class StudentTest {

public static void main(String[] args) {
SqlSession sqlSession=SqlSessionFactoryUtil.openSession();
StudentMapper studentMapper=sqlSession.getMapper(StudentMapper.class);
Student student=new Student("小强",11);
int result=studentMapper.add(student);
sqlSession.commit();
if(result>0){
System.out.println("添加成功!");
}
}

}

 

以上则完成了mybatis的操作数据库。

你可能感兴趣的:(笔记)