Mybatis
-
环境配置
mybatis的jar包下载地址:https://github.com/mybatis/mybatis-3/releases
mybatis和Spring整合jar包下载地址:https://github.com/mybatis/spring/releases -
配置mybatis全局配置文件
<?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> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.cj.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC"/> <property name="username" value="root"/> <property name="password" value="521314"/> </dataSource> </environment> </environments> <mappers> <mapper resource="com/xdd/model/User.xml"/> </mappers> </configuration>
-
配置映射文件
<?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="user"> <select id="findNameById" resultType="com.xdd.model.User" parameterType="int" > SELECT *FROM user WHERE id=#{id}; </select> <select id="findUser" resultType="com.xdd.model.User" parameterType="String" > //模糊查询 SELECT *FROM user WHERE username like '%${value}%'; </select> //插入 <insert id="addUser" parameterType="com.xdd.model.User"> INSERT into user (username,sex,birthday,address) VALUE (#{username},#{sex},#{birthday},#{address}); </insert> //删除 <delete id="deleteUser" parameterType="String"> DELETE FROM user WHERE username = '${value}' </delete> //更新 <update id="updateUser" parameterType="com.xdd.model.User"> UPDATE user SET sex=#{sex},address=#{address} where id = #{id}; </update> </mapper>
-
查询&插入&删除
public void test1() throws IOException { //读取配置文件 String resource = "mybatisConfig.xml"; InputStream is = Resources.getResourceAsStream(resource); SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is); //获取session对象 SqlSession session=sessionFactory.openSession(); User user=session.selectOne("findNameById",10); //返回list集合 List<User> list=session.selectList("findUser","张"); //插入 User user=new User("xdd","男",new Date(),"河南"); session.insert("addUser",user); //删除 session.delete("deleteUser","xdd"); //更新 User user = new User("xdd","男",null,"北京"); session.update("updateUser",user); session.commit(); }
-
插入后返回主键
<insert id="insertUser2" parameterType="com.xdd.model.User"> //keyProperty表示主键,resultType表示主键类型 <selectKey keyProperty="id" resultType="int" order="AFTER"> //主键是UUID时:resultType="String" Order="Before" SELECT LAST_INSERT_ID(); //主键是UUID时:SELECT UUID(); </selectKey> INSERT into user (username,sex,birthday,address) VALUE (#{username},#{sex},#{birthday},#{address}); </insert>
-
Mybatis通过mapper代理实现dao的编写 例:
-
编写UserMapper接口:(只能有一个参数)
public interface UserMapper { public void save(User user); public User findUserById(int id); }
-
编写UserMapper.xml配置文件:(namespace要和接口名相同)
<?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="com.xdd.mapper.UserMapper"> <insert id="save" parameterType="com.xdd.model.User"> INSERT into user (username,sex,birthday,address) VALUE (#{username},#{sex},#{birthday},#{address}); </insert> <select id="findUserById" parameterType="int" resultType="com.xdd.model.User"> SELECT *FROM user WHERE id = #{id}; </select> </mapper>
-
通过session的getMapper方法获取代理
UserMapper userMapper=session.getMapper(UserMapper.class); userMapper.save(user);
-
多表查询
-
一对一 实现(模型里面包含模型)
OrderMapper.javapublic interface OrderMapper { public Orders findOrderById(int id); }
OrderMapper.xml
<mapper namespace="com.xdd.mapper.OrderMapper"> <resultMap id="orderMap" type="orders"> <id property="id" column="id"></id> <association property="user" javaType="User"> <id column="id" property="id"></id> </association> </resultMap> <select id="findOrderById" resultMap="orderMap" parameterType="int"> select * from orders,user where orders.user_id=user.id and orders.id=#{id} </select> </mapper>
-
一对多
<resultMap id="orderMap2" type="orders"> <id column="id" property="id"></id> //User对象模型 <association property="user" javaType="user"> <id property="id" column="user_id"/> </association> //集合模型 <collection property="orderDetails" ofType="orderDetail"> //****参数是ofType <id column="detail_id" property="id"></id> </collection> </resultMap> <select id="findOrderById2" resultMap="orderMap2" parameterType="int"> select o.*,u.username,u.address,od.id detail_id,od.items_id,od.items_num from orders o,user u,orderdetail od where o.user_id=u.id and o.id=od.orders_id and o.id=#{id} </select>
-
多对多
<resultMap id="userMap" type="user"> <id column="id" property="id"/> <result column="username" property="username"/> <result column="address" property="address"/> //用户的订单集合 <collection property="ordersList" ofType="orders"> <id column="order_id" property="id"/> <result column="createtime" property="createtime"/> //订单详情集合 <collection ="orderDetails" ofType="orderDetail"> <id column="detail_id" property="id"/> <result column="items_num" property="itemsNum"/> //订单 <association property="items" javaType="items"> <id column="item_id" property="id"/> <result column="name" property="name"/> <result column="detail" property="detail"/> <result column="price" property="price"/> </association> </collection> </collection> </resultMap> <select id="findUser" resultMap="userMap"> SELECT user.id,user.username,user.address, orders.id order_id,orders.createtime, orderdetail.id detail_id,orderdetail.items_num, items.id item_id,items.name,items.price FROM user,orders,orderdetail,items WHERE orders.user_id=user.id and orders.id=orderdetail.orders_id and orderdetail.id=items.id </select>
-
逆向工程:根据数据库表生成简单的代码
-
导入jar包:mybatis-generator-core-1.3.2.jar
-
编写配置文件:
<!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> <generatorConfiguration> <context id="mysqlTables" targetRuntime="MyBatis3"> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC" userId="root" password="521314"> </jdbcConnection> <javaTypeResolver > <property name="forceBigDecimals" value="false" /> </javaTypeResolver> <javaModelGenerator targetPackage="com.xdd.model" targetProject=".\src"> <property name="enableSubPackages" value="true" /> <property name="trimStrings" value="true" /> </javaModelGenerator> <sqlMapGenerator targetPackage="com.xdd.mapper" targetProject=".\src"> <property name="enableSubPackages" value="true" /> </sqlMapGenerator> <javaClientGenerator type="XMLMAPPER" targetPackage="com.xdd.mapper" targetProject=".\src"> <property name="enableSubPackages" value="true" /> </javaClientGenerator> <table tableName="items" domainObjectName="Items" ></table> <table tableName="orderdetail" domainObjectName="OrderDetail" ></table> <table tableName="orders" domainObjectName="Orders" ></table> <table tableName="user" domainObjectName="User" ></table> </context> </generatorConfiguration>
-
执行方法生成代码:
public static void main(String[] args) throws Exception{ List<String> warnings=new ArrayList<String>(); boolean overwrite=true; File configFile=new File("src/generator.xml"); ConfigurationParser cp=new ConfigurationParser(warnings); Configuration config=cp.parseConfiguration(configFile); DefaultShellCallback callback=new DefaultShellCallback(overwrite); MyBatisGenerator myBatisGenerator=new MyBatisGenerator(config,callback,warnings); myBatisGenerator.generate(null); }
-