MyBatis开发步骤

1. 添加jar文件 mybatis-3.0.5.jar
2. 下创建 MyBatise.xml
代码如下:


“http://mybatis.org/dtd/mybatis-3-config.dtd”>

<environments default="development">
    <environment id="development">
        <transactionManager type="JDBC" />

        <dataSource type="POOLED">
            <property name="driver" value="com.microsoft.sqlserver.jdbc.SQLServerDriver" />
            <property name="url" value="jdbc:sqlserver://127.0.0.1:1433;databaseName=ShoppingCart" />
            <property name="username" value="sa" />
            <property name="password" value="123@qwe" />
        </dataSource>

    </environment>
</environments>


3 .创建maper 文件 ProductDao.xml


“http://mybatis.org/dtd/mybatis-3-mapper.dtd”>

<select id="searchAll"  resultType="com.shoppingcart.entity.Product">
    select ProductName as productName, Id as id, Price as price,img as Image from products 
</select>


4 在 MyBatise.xml 的 元素的最后添加如下代码
…..

<mappers>
    <mapper resource="com/shoppingcart/dao/mybatise/ProductDao.xml" />
</mappers>

5.封装 SqlSessionFactory
public class SqlSessionFactoryUtil {

static SqlSessionFactory sqlSessionFactory;

static {
    String resource = "com/shoppingcart/util/MyBatise.xml";
    Reader reader = null;
    try {
        reader = Resources.getResourceAsReader(resource);
    } catch (IOException e) {
        e.printStackTrace();
    }
    sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
}

public static SqlSession getSqlSession()
{
    return sqlSessionFactory.openSession();
}

}
6 创建 ProductDaoImpl
public class ProductDaoImpl implements ProductDao {

public List<Product> searchAll() throws SQLException {
        SqlSession session = SqlSessionFactoryUtil.getSqlSession();
        List<Product> list = session.selectList("com.shoppingcart.dao.ProductDao.searchAll");
        return list;
}

}

7 测试
public static void main(String[] args) {

    try {
        List<Product> list = new ProductDaoImpl().searchAll();
        for(Product p:list)
        {
            System.out.println(p.getId()+"\t"+p.getProductName());
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

你可能感兴趣的:(java,mybatis)