一、基本引入
1、配置
mysql8+myBatis
教程:狂神
官网:入门_MyBatis中文网
项目地址:地址项目目录
4.0.0 org.example gamespom 1.0-SNAPSHOT // 子项目名fly// 依赖 myBatis mysql junit fly // 配置maven环境 utf-8 org.mybatis mybatis3.5.6 mysql mysql-connector-java5.1.47 junit junit4.12 // 配置未在resource中导入,项目中的后缀名为xml和properties文件进入预加载 8 8 UTF-8 src/main/resources ***.xml true src/main/java ***.xml true
子模块pom
games org.example 1.0-SNAPSHOT 4.0.0 flysrc/main/resources ***.xml true src/main/java **/*.xml true 8 8 UTF-8
项目目录结构:
1、新建User类,
package com.npb.pojo; public class User { private String username; private String id; private String password; @Override public String toString() { return "User{" + "id='" + id + ''' + ", password='" + password + ''' + ", username='" + username + ''' + '}'; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getPassword(){ return password; } public void setPassword(String password){ this.password=password; } public String getUsername(){ return username; } public void setUsername(String username){ this.username=username; } }
对应
2、创建接口UserDao
package com.npb.dao; import com.npb.pojo.User; import java.util.List; public interface UserDao { ListgetUserList(); }
3、连接数据库
新建MyBatisUtils类
package com.npb.utils; 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 java.io.IOException; import java.io.InputStream; public class MyBatisUtils { private static SqlSessionFactory sqlSessionFactory; static { // 数据库连接信息文件 String resource = "mybatis-config.xml"; InputStream inputStream = null; try { inputStream = Resources.getResourceAsStream(resource); } catch (IOException e) { e.printStackTrace(); } sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } // 当前连接 public static SqlSession getSqlSession() { return sqlSessionFactory.openSession(); } }
新建mybatis-config.xml
// UserMapp.xml // // // // // select * from news.user // //
4、新建UserMapper.xml
5、测试连接
package com.npb.dao; import com.npb.pojo.User; import com.npb.utils.MyBatisUtils; import org.apache.ibatis.session.SqlSession; import org.junit.Test; import java.util.List; public class UserDaoTest { @Test public void test() { SqlSession sqlSession = MyBatisUtils.getSqlSession(); UserDao userDao = sqlSession.getMapper(UserDao.class); ListuserList = userDao.getUserList(); for (User user : userList) { System.out.println(user); } sqlSession.close(); } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)