附上sql:
CREATE TABLE `student` ( `sid` char(10) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL, `sname` char(20) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL, `sc` double(5, 2) NULL DEFAULT NULL, `sm` double(5, 2) NULL DEFAULT NULL, `se` double(5, 2) NULL DEFAULT NULL, `st` double(5, 2) NULL DEFAULT NULL, PRIMARY KEY (`sid`) USING BTREE ) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact; SET FOREIGN_KEY_CHECKS = 1; //然后自己再去插数据进行调试实体类:
@AllArgsConstructor @NoArgsConstructor @Data public class Student { private String sid; private String sname; private double sc ; private double sm ; private double se ; private double st ; }映射文件:
StudengtMapper.xml
Mybatis配置文件:select * from student where sid = #{sid}
conf.xml
动态代理方式建接口类映射
StudentMapper接口:
package org.koma.entity; public interface StudentMapper { //方法名和id值一致,输入参数类型与parameterType一致,方法返回值与resultType一致 Student queryStudentById(String sid); }测试类
package org.koma.entity; import java.io.IOException; import java.io.Reader; 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 TestMyBatis { public static void main(String[] args) throws IOException { //加载MyBatis配置文件(为了访问数据库) Reader reader = Resources.getResourceAsReader("conf.xml") ; SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader) ;//SqlSessionFactory工厂 //session - connection。session就能进行数据库 *** 作 SqlSession session = sessionFactory.openSession() ; //第一种方法,基础方式CRUD 使用statment定位namespace和id String statement = "org.koma.entity.StudentMapper." + " queryStudentById" ;//namespace + id Student student = session.selectOne(statement,"2017160402") ;//selectOne(statement,arg)查询一个,selectList(statement,arg)查询全部 System.out.println("通过直接statement+select_id的方式映射mapper.xml :n"+student.toString()+"n"); //第二种方法(动态代理方式建接口类映射):通过StudenMapper接口映射不同数据库mapper.xml,StudenMapper接口类名跟mapper.xml的namespace一致 StudentMapper studentmapper = session.getMapper(StudentMapper.class); Student student2 = studentmapper.queryStudentById("2017160402");//接口的xx方法 //如果是增删改 *** 作,需要执行session.commit()提交事务 (conf指定的原因) System.out.println("通过通过StudenMapper接口映射不同数据库mapper.xml :n"+student2.toString()); session.close(); } }
Mybatis其他相关:
Mybatis中输入参数说明及其他配置
Mybatis输出参数实例
Mybatis调用存储过程实例
Mybatis动态SQL及关联查询实例
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)