用JavaSE简单入门MyBatis连接MySQL…,javasemybatis
分享于 点击 17091 次 点评:130
用JavaSE简单入门MyBatis连接MySQL…,javasemybatis
在Netbeans中新建一个 Java——Java应用程序 项目,其目录结构如下:需要准备和下载的jar库: 1、mybatis-3.4.1.jar 2、mysql-connector-java-5.1.39-bin.jar(安装MySQL的时候,勾选安装Connector.J后会附带有,在MySQL 安装目录/Connector.J 5.1 里面)
添加好库后,就可以开始干活了。 首先得在MySQL里面建立数据库和表格: 文件student.sql——不过这个文件并不参与MyBatis。我单独登录MySQL Client然后在命令行输入SQL语句创建的表格
CREATE DATABASE
STUDENT_MANAGER;
USE
STUDENT_MANAGER;
CREATE TABLE STUDENT_TBL ( STUDENT_ID VARCHAR(255) PRIMARY KEY, STUDENT_NAME VARCHAR(10) NOT NULL, STUDENT_SEX VARCHAR(10), STUDENT_BIRTHDAY DATE, CLASS_ID VARCHAR(255) ); INSERT INTO STUDENT_TBL (STUDENT_ID, STUDENT_NAME, STUDENT_SEX, STUDENT_BIRTHDAY, CLASS_ID) VALUES (123456, '某某某', '女', '1980-08-01', 121546 ) |
然后我们开始编写类: 首先,我们把这个STUDENT_TBL表的表头编写成一个POJO类(只含有成员变量,setter和getter的简单Java对象“Plain Ordinary Java Object”) 文件StudentEntity.Java
package mybatishelloworld; import java.io.Serializable; import java.util.Date; public class StudentEntity implements Serializable { private static final long serialVersionUID = 3096154202413606831L; private Date studentBirthday; private String studentID; private String studentName; private String studentSex; public Date getStudentBirthday() { return studentBirthday; } public String getStudentID() { return studentID; } public String getStudentName() { return studentName; } public String getStudentSex() { return studentSex; } // Setter …… …… …… …… public void setStudentBirthday(Date studentBirthday) { this.studentBirthday = studentBirthday; } public void setStudentID(String studentID) { this.studentID = studentID; } public void setStudentName(String studentName) { this.studentName = studentName; } public void setStudentSex(String studentSex) { this.studentSex = studentSex; } public void println(){ System.out.print(this.studentID+" "); System.out.print(this.studentName+" "); System.out.print(this.studentSex+" "); System.out.println(this.studentBirthday); } } |
接着我们建立一个Mapper接口——于是,我们为什么需要一个映射(Mapper)接口呢? 原因我们看看代码就懂了: 文件StudentMapper.java
package mybatishelloworld; import java.util.List; public interface StudentMapper { public StudentEntity getStudent(String studentID); public StudentEntity getStudentAndClass(String studentID); public List getStudentAll(); public void insertStudent(StudentEntity entity); public void deleteStudent(StudentEntity entity); public void updateStudent(StudentEntity entity); } |
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="mybatishelloworld.StudentMapper"> <!-- Student类的sql语句文件StudentMapper.xml resultMap标签:表字段与属性的映射。 Select标签:查询sql。 由于StudentEntity已经在mybatis-config.xml里面 映射成了mybatishelloworld.StudentEntity,即 mybatishelloworld目录下的StudentEntity.java类 所以这里的type后面直接跟着StudentEntity,MyBatis就知道如何寻找使用 StudentEntity类了。 --> <resultMap type="StudentEntity" id="studentResultMap"> <id property="studentID" column="STUDENT_ID"/> <result property="studentName" column="STUDENT_NAME"/> <result property="studentSex" column="STUDENT_SEX"/> <result property="studentBirthday" column="STUDENT_BIRTHDAY"/> </resultMap> <!-- 查询学生,根据id --> <select id="getStudent" parameterType="String" resultType="StudentEntity" resultMap="studentResultMap"> <![CDATA[ SELECT * from STUDENT_TBL ST WHERE ST.STUDENT_ID = #{studentID} ]]> </select> <!-- 查询学生列表 --> <select id="getStudentAll" resultType="StudentEntity" resultMap="studentResultMap"> <![CDATA[ SELECT * from STUDENT_TBL ]]> </select> </mapper> |
为了使用Mybatis,我们还得个它一个配置文件,配置所使用的数据库类型,数据库连接地址,用户名和密码等等,这个文件的配置如下: 文件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> <!-- typeAliases这玩意儿一定要放在environment的开头,可以参照报错的顺序设置: 顺序同错误提示信息一致: 元素类型为 "configuration" 的内容必须匹配 "(properties?,settings?, typeAliases?,typeHandlers?,objectFactory?,objectWrapperFactory?, reflectorFactory?,plugins?,environments?,databaseIdProvider?,mappers?) —————by http://blog.csdn.net/liu578182160/article/details/50747390 --> <typeAliases> <typeAlias alias="StudentEntity" type="mybatishelloworld.StudentEntity" /> </typeAliases> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/student_manager?useSSL=true"/> <property name="username" value="root"/> <property name="password" value="rootOfPasswd"/> </dataSource> </environment> </environments> <!-- 创建MyBatis的mapper配置文件 创建MyBatis配置文件:mybatis-config.xml。 Mappers标签:加载MyBatis中实体类的SQL映射语句文件。 --> <mappers> <mapper resource="mybatishelloworld/StudentMapper.xml" /> </mappers> </configuration> |
最后我们在MainClass的main函数里面,测试我们的整个配置 文件MainClass.java
package
mybatishelloworld;
import java.io.IOException; import java.io.InputStream; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; 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 MainClass { public static void main(String[] args) { String resource = "mybatishelloworld/mybatis-config.xml"; //告诉MyBatis核心配置文件在哪里 InputStream inputStream = null; try { inputStream = Resources.getResourceAsStream(resource); }catch(IOException ex){Logger.getLogger(MainClass.class.getName()).log(Level.SEVERE, null, ex);} //打开SQL对话工厂 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); try (SqlSession session = sqlSessionFactory.openSession()) { //用工厂生成一个对话 //这里是精华,session用getMapper方法从xml里面生成了StudentMapper接口的实现类 StudentMapper mapper = (StudentMapper) session.getMapper(StudentMapper.class); StudentEntity se = mapper.getStudent("123456"); //于是这个类就有了具体的getStudent方法 se.println(); List list=mapper.getStudentAll(); list.forEach((s)->{ s.println(); }); } }//End-Of-Main } |
在Netbeans编译运行后的结果:
相关文章
- 暂无相关文章
用户点评