在Eclipse中使用Mybatis

1.新建一个Maven项目,在依赖关系中加入以下依赖关系:

<dependency>
      <groupId>org.mybatisgroupId>
      <artifactId>mybatisartifactId>
      <version>3.4.4version>
    dependency>
    <dependency>
        <groupId>mysqlgroupId>
        <artifactId>mysql-connector-javaartifactId>
        <version>6.0.5version>
    dependency>

2.新建xml配置文件



<configuration>
  <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://127.0.0.1:3306/vd01"/>
        <property name="username" value="videowsdemo"/>
        <property name="password" value="videowsdemo"/>
      dataSource>
    environment>
  environments>
  <mappers>
    <mapper resource=""/>
  mappers>
configuration>

3.bean和数据库的映射文件



<mapper namespace="com.lxl.app.config.UserInfoMapper">
    <select id="GetUserInfoByID" parameterType="int" resultType="com.lxl.app.beans.UserInfo">
        select * from `user_info` where account_id = #{id}
    <lect>
mapper>

4.测试

public static void main( String[] args ) throws Exception
    {
        //构建SqlSessionFactory
        String resource = "com/lxl/app/config/config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession ss = sqlSessionFactory.openSession();
        try{
            UserInfo ui = ss.selectOne("com.lxl.app.config.UserInfoMapper.GetUserInfoByID",2);
            if(ui != null){
                System.out.println("nickname:"+ui.getNickname());
                System.out.println("email:"+ui.getEmail());
            }
        }finally{
            ss.close();
        }





    }

你可能感兴趣的:(Java,Maven)