MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。MyBatis 只是一个半自动化的ORM实现,需要我们自己写sql,而不像hibernate那样,直接定义好实体与数据表的映射就行。
- 导入jar包:
- 注意:画出来的那几个是用来配置batis的,其他的是写DBUtils.java用到的
- 创建entity包,在entity包中创建实体类(UserInfo.java)
-
1 package entity; 3 public class UserInfo { 4 private Integer id; 5 private String name; 6 private String password; 7 public Integer getId() { 8 return id; 9 } 10 public void setId(Integer id) { 11 this.id = id; 12 } 13 public String getName() { 14 return name; 15 } 16 public void setName(String name) { 17 this.name = name; 18 } 19 public String getPassword() { 20 return password; 21 } 22 public void setPassword(String password) { 23 this.password = password; 24 } 25 public UserInfo(Integer id, String name, String password) { 26 super(); 27 this.id = id; 28 this.name = name; 29 this.password = password; 30 } 31 public UserInfo(String name, String password) { 32 super(); 33 this.name = name; 34 this.password = password; 35 } 36 public UserInfo() { 37 super(); 38 // TODO Auto-generated constructor stub 39 } 40 @Override 41 public String toString() { 42 return "UserInfo [id=" + id + ", name=" + name + ", password=" + password + "]"; 43 } 47 }
- 创建配置文件(batis-config.xml)
-
1 <configuration> 2 <environments default="development"> 3 <environment id="development"> 4 <transactionManager type="JDBC" /> 5 <dataSource type="POOLED"> 6 <property name="driver" value="${driver}" /> 7 <property name="url" value="${url}" /> 8 <property name="username" value="${username}" /> 9 <property name="password" value="${password}" /> 10 </dataSource> 11 </environment> 12 </environments> 13 </configuration>
注意:<Configuration>标签前面需要配置
-
1 <!DOCTYPE configuration 2 PUBLIC "-//mybatis.org//DTD Config 3.0//EN" 3 "http://mybatis.org/dtd/mybatis-3-config.dtd"> 4 <configuration>
- 创建属性文件(db.preperties)
-
1 driver=oracle.jdbc.OracleDriver 2 url=jdbc:oracle:thin:@localhost:1521:orcl 3 username=test2 4 password=123456
- 在配置文件中(batis-config.xml)加载属性文件(db.preperties),为了获取属性文件中定义的值。放置<environments>前面。
-
1 <properties resource="db.properties"> 2 </properties>创建tools包,在tools包中创建工具类(DBUtils.java)
- 创建tools包,在tools包中创建工具类(DBUtils.java)
-
1 package tools; 2 3 4 import java.io.IOException; 5 import java.io.Reader; 6 7 import org.apache.ibatis.io.Resources; 8 import org.apache.ibatis.session.SqlSession; 9 import org.apache.ibatis.session.SqlSessionFactory; 10 import org.apache.ibatis.session.SqlSessionFactoryBuilder; 11 12 public class DBUtils { 13 private static SqlSessionFactory factory; 14 static { 15 16 try { 17 //读取配置文件 18 Reader reader = Resources.getResourceAsReader("batis-config.xml"); 19 //创建SqlSessionFactory 20 factory=new SqlSessionFactoryBuilder().build(reader); 21 } catch (IOException e) { 22 e.printStackTrace(); 23 } 24 } 25 /** 26 * 打开session 27 * @param flag 28 * @return 29 */ 30 public static SqlSession getSession(boolean flag) { 31 return factory.openSession(flag); 32 } 33 /** 34 * 关闭session 35 * @param session 36 */ 37 public static void close(SqlSession session) { 38 if(session!=null) { 39 session.close(); 40 } 41 } 42 /** 43 * 事务回滚 44 * @param session 45 */ 46 public static void rollback(SqlSession session) { 47 if(session!=null) { 48 session.rollback(); 49 } 50 } 51 /** 52 * 事务提交 53 * @param session 54 */ 55 public static void commit(SqlSession session) { 56 if(session!=null) { 57 session.commit(); 58 } 59 } 60 61 }
- 创建映射文件(dao包->>UserInfoMapper接口及定义方法->>创建映射文件)(注意:橙色的id名称就是接口中定义的方法名称,两者要一致)
-
1 <mapper namespace="dao.UserInfoMapper"> 2 <select id="login" parameterType="UserInfo" resultMap="userInfoResult"> 3 select * from userInfo where name=#{username} and password=#{password} 4 </select> 5 6 <select id="findAll" resultMap="userInfoResult"> 7 select * from userInfo 8 </select> 9 10 <insert id="insert"> 11 insert into userInfo(name,password) values(#{username},#{password}) 12 </insert> 13 14 <update id="update" parameterType="UserInfo" > 15 update userInfo set name=#{username},password=#{password} where id=#{id} 16 </update> 17 18 <delete id="delete" parameterType="int"> 19 delete from userInfo where id=#{id} 20 </delete> 21 </mapper> // 注意:上面红色的是需要在batis-config.xml定义的别名,若不定义,则应写成:entity.UserInfo
- 在batis-config.xml定义别名:
-
1 <typeAliases> 2 <typeAlias type="entity.UserInfo" alias="UserInfo"/> 3 </typeAliases> 4 5 6 //(entity.UserInfo:为包名+实体类名 UserInfo:别名)
- 上面绿色的,若实体类中的属性与数据库的属性没有对应,则需要进行属性映射(放在<mapper>标签下面)
-
1 <resultMap type="entity.UserInfo" id="userInfoResult"> 2 <id column="id" property="id" /> 3 <result property="username" column="name" /> 4 <result property="password" column="password" /> 5 </resultMap>
- 创建测试类(1)采用select方法
-
1 @Test 2 public void testMybatis() { 3 4 SqlSession session = null; 5 try { 6 session = DBUtils.getSession(true); 7 UserInfo userInfo = new UserInfo("TOM", "123456"); 8 UserInfo user = session.selectOne("dao.UserInfoMapper.login", userInfo); 9 if (user == null) { 10 System.out.println("登錄失敗!"); 11 } else { 12 System.out.println("登錄成功!"); 13 } 14 } catch (Exception e) { 15 e.printStackTrace(); 16 } finally { 17 if (session != null) { 18 DBUtils.close(session); 19 } 20 } 21 }
采用getMapper()方法
-
1 @Test 2 public void testMapper() { 3 SqlSession session = null; 4 try { 5 6 session = DBUtils.getSession(true); 7 UserInfo userInfo = new UserInfo("TOM", "123456"); 8 UserInfo user = session.getMapper(UserInfoMapper.class).login(userInfo); 9 if (user == null) { 10 System.out.println("登录失败"); 11 } else { 12 System.out.println("登录成功"); 13 } 14 } catch (Exception e) { 15 e.printStackTrace(); 16 } finally { 17 if (session != null) { 18 DBUtils.close(session); 19 } 20 } 21 }
原文地址:https://www.cnblogs.com/RobotMujie/p/8453662.html
时间: 2024-11-05 23:22:17