一共需要4个东西
1、主程序(我称之为主操作程序)
主程序的主要任务是创建一个sqlsession:
(1)声明一个值为总配置文件的
String String s="conf.xml";
(2)利用
inputStream=Resources.getResourceAsStream(s);
创建一个InputStream,这是一个通向主配置文件的字节流
(3)创建一个sqlsessionfactory,
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
,这个sqlsession工厂的任务就是打开一个sqlsession
(4)利用sqlsession得到接口的对象:
GetstudentInfo getstudentInfo = sqlSession.getMapper(GetstudentInfo.class);
(这种类型的方法都是通过反射来实现的,即你传了一个对象的class过去,就可以通过反射方式来生成这个对象)
(5)得到所需要的bean对象
Student student = getstudentInfo.getStudent(1);
如果没有接口的话,可以使用
Student student=sqlSession.selectOne("shenzhigongsi.MaiziMybatis.mapper.StudentMapper.selectStudent",1);
来访问这个mapper中的方法,效果是一样的
2、接口Info
只有一个实现方法就是public Student getStudent(int id);
3、主配置文件
在configuration标签中主要有environment
<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/shen_db" /> <property name="username" value="root" /> <property name="password" value="123456" /> </dataSource> </environment> </environments>
另一个标签就是mapper,用来映射到mapper文件的
<mappers> <mapper resource="com/shenzhi/mybatis/resource/studentmapper.xml" /> </mappers>
mapper的resource属性是路径,而不是包结构,是以/隔开的,而不是.
4、mapper文件
<mapper namespace="shenzhigongsi.MY_mybatis.GetstudentInfo"> <select id="getStudent" parameterType="int" resultType="shenzhigongsi.MY_mybatis.Student"> select birthday from student where id =#{id} </select> </mapper>
namespace是接口的完全限定包名加上接口名,这样才可以知道这是映射哪一个接口的,<select>是用来定义sql语句的,id属性是接口的方法名,parameterType是参数的类型,resultType是返回类型,这里返回的是一个student对象,所以要加上student的完全限定包名
Student类