首页 > 代码库 > mybatis(基于annotation的方法知道就行了)
mybatis(基于annotation的方法知道就行了)
MyBatisUtil.java
UserMapper.java
package edu.hhxy.btais.util; 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; public class MyBatisUtil { private static SqlSession session = null; public static SqlSession createSeqSession() { try { // 1、创建配置文件(mybatis-config.xml)的输入流 InputStream is = Resources .getResourceAsStream("mybatis-config.xml"); // 2、创建SQLSessionFactory SqlSessionFactory factory = new SqlSessionFactoryBuilder() .build(is); // 3、创建SQLSessioin session = factory.openSession(); } catch (IOException e) { e.printStackTrace(); } return session; } public static void closeSeqSession(SqlSession sqlSession) { try { sqlSession.close(); } catch (Exception e) { e.printStackTrace(); } finally { sqlSession = null; } } }
jdbc.properties
?
1 2 3 4 | username=root password=root url=jdbc:mysql: //localhost:3306/mybatis driver=com.mysql.jdbc.Driver |
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> <package name="edu.hhxy.btais" /> </typeAliases> <!-- 在properties之后加上typeAliases --> <environments default="development"> <environment id="development"> <transactionManager type="JDBC" /> <!-- 配置mybatis的pooled的数据源 --> <dataSource type="POOLED"> <property name="driver" value="${driver}" /> <property name="url" value="${url}" /> <property name="username" value="${username}" /> <property name="password" value="${password}" /> </dataSource> </environment> </environments> <mappers> <package name="edu.hhxy.btais"/> </mappers> </configuration>
TestMybatisByMapperAnnotation
package edu.hhxy.btais; import org.apache.ibatis.session.SqlSession; import org.junit.Test; import edu.hhxy.btais.mapper.UserMapper; import edu.hhxy.btais.util.MyBatisUtil; public class TestMybatisByMapperAnnotation { @Test public void addTest() { SqlSession session = null; try { session = MyBatisUtil.createSeqSession(); User u = new User(); u.setNickname("猪八戒"); u.setPassword("123"); u.setType(1); u.setUsername("bajie"); session.getMapper(UserMapper.class).add(u); session.commit(); } catch (Exception e) { e.printStackTrace(); } finally { MyBatisUtil.closeSeqSession(session); } } }
只需要了解即可。
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。