@Alias注解使用不生效
基础配置文件及项目结构
父工程pom.xml
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.example</groupId> <artifactId>Mybatis</artifactId> <version>1.0-SNAPSHOT</version> <packaging>pom</packaging> <modules> <module>Mybatis01</module> <module>Mybatis02</module> <module>Mybatis03</module> </modules> <properties> <maven.compiler.source>17</maven.compiler.source> <maven.compiler.target>17</maven.compiler.target> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <!-- 导入依赖 --> <dependencies> <!--mysql驱动--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.33</version> </dependency> <!--mybatis--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.7</version> </dependency> <!--junit--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13.2</version> </dependency> <!--lombok--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.30</version> </dependency> <!--log4j日志--> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> </dependencies> <!--在build中配置resources,来防止我们资源导出失败的问题--> <build> <resources> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>true</filtering> </resource> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>true</filtering> </resource> </resources> </build> </project>
子工程
bean
package com.wdw.bean; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import org.apache.ibatis.type.Alias; @Data @Alias("use") @AllArgsConstructor @NoArgsConstructor public class User { private Integer id; private String name; private String password; }
dao
mapper接口
package com.wdw.dao; import com.wdw.bean.User; import java.util.List; public interface UserMapper { // 返回所有用户 List<User> getUserList(); // 根据id查询用户 User getUserById(int id); // 添加单个用户 int addUser(User user); // 根据id修改用户 int updateUserById(User user); // 根据id删除用户 int deleteUser(int i); }
mapper.xml
<?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"> <!-- namespace=绑定一个对应的Dao/Mapper接口 --> <mapper namespace="com.wdw.dao.UserMapper"> <resultMap id="UserMap" type="com.wdw.bean.User"> <!--mybatis数据库中的字段,property实体类中的属性--> <result column="u_id" property="id"/> <result column="u_name" property="name"/> <result column="u_pwd" property="password"/> </resultMap> <!--select查询语句--> <!--获取所有的用户--> <!-- <select id="getUserList" resultType="user" resultMap="UserMap">--> <select id="getUserList" resultType="use" resultMap="UserMap"> select * from mybatis.user; </select> <!--根据id查询用户信息--> <select id="getUserById" resultType="map" parameterType="int" resultMap="UserMap"> select * from mybatis.user where u_id = #{id}; </select> <!--添加单个用户--> <insert id="addUser" parameterType="user"> insert into mybatis.user (u_id, u_name, u_pwd) values (#{id}, #{name}, #{password}) </insert> <!--根据id修改用户--> <update id="updateUserById" parameterType="user"> update mybatis.user set u_name=#{name}, u_pwd =#{password} where u_id = #{id} </update> <!--根据id删除用户--> <select id="deleteUser" parameterType="map"> delete from mybatis.user where u_id=#{id} </select> </mapper>
util
package com.wdw.utils; import lombok.Getter; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import java.io.IOException; import java.io.InputStream; // sqlSessionFactory ---> SqlSession 通过sqlSession工厂获取sqlSession对象 public class MybatisUtils { // 既然有了 SqlSessionFactory,顾名思义,我们就可以从中获得 SqlSession 的实例了。 // SqlSession 完全包含了面向数据库执行 SQL 命令所需的所有方法。 private static final @Getter SqlSessionFactory sqlSessionFactory; static { String resource = "mybatis-config.xml"; try { // 使用Mybatis第一步:获取sqlSessionFactory对象 InputStream inputStream = Resources.getResourceAsStream(resource); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } catch (IOException e) { throw new RuntimeException(e); } } }
resource
<?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核心配置文件--> <configuration> <!-- 引入外部文件 --> <properties resource="db.properties"/> <!-- 可以给实体类起别名 --> <typeAliases> <!--在UserMapper中参数类型的名字与此'alias'属性值比较时,首字母会忽略大小写--> <!-- <typeAlias type="com.wdw.bean.User" alias="user"/>--> <package name="com.wdw.bean"/> </typeAliases> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="${driver}"/> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> </dataSource> </environment> </environments> <!-- 每一个Mapper.xml都需要在mybatis核心配置文件中注册! --> <mappers> <mapper resource="com/wdw/dao/UserMapper.xml"/> <!-- <mapper class="com.wdw.dao.UserMapper"/>--> </mappers> </configuration>
test
package com.wdw.dao; import com.wdw.bean.User; import org.apache.ibatis.session.SqlSession; import org.junit.Test; import com.wdw.utils.MybatisUtils; import java.util.List; public class UserMapperTest { @Test public void getUserList() { // 获取sqlSession对象 SqlSession sqlSession = MybatisUtils.getSqlSessionFactory().openSession(); UserMapper userMapper = sqlSession.getMapper(UserMapper.class); // 执行sql 获取sql返回的结果 List<User> userList = userMapper.getUserList(); // 遍历容器 userList.forEach(System.out::println); // 关闭流 sqlSession.close(); } }
使用包扫描
在四种映射器方法,使用包扫描最为便捷,所以就想搭配@Alias注解使用
报错信息
E:\JDK\17\bin\java.exe -Dvisualvm.id=11644430586100 -ea -Didea.test.cyclic.buffer.size=1048576 "-javaagent:E:\IDEA\IntelliJ IDEA 2023.3.3\IDEA\IntelliJ IDEA 2023.3.4\lib\idea_rt.jar=54239:E:\IDEA\IntelliJ IDEA 2023.3.3\IDEA\IntelliJ IDEA 2023.3.4\bin" -Dfile.encoding=UTF-8 -classpath "E:\IDEA\IntelliJ IDEA 2023.3.3\IDEA\IntelliJ IDEA 2023.3.4\lib\idea_rt.jar;E:\IDEA\IntelliJ IDEA 2023.3.3\IDEA\IntelliJ IDEA 2023.3.4\plugins\junit\lib\junit5-rt.jar;E:\IDEA\IntelliJ IDEA 2023.3.3\IDEA\IntelliJ IDEA 2023.3.4\plugins\junit\lib\junit-rt.jar;E:\My_project\2024-project\Mybatis\Mybatis02\target\test-classes;E:\My_project\2024-project\Mybatis\Mybatis02\target\classes;E:\Java_Configuration_Library\maven_repository\com\mysql\mysql-connector-j\8.0.33\mysql-connector-j-8.0.33.jar;E:\Java_Configuration_Library\maven_repository\com\google\protobuf\protobuf-java\3.21.9\protobuf-java-3.21.9.jar;E:\Java_Configuration_Library\maven_repository\org\mybatis\mybatis\3.5.7\mybatis-3.5.7.jar;E:\Java_Configuration_Library\maven_repository\junit\junit\4.13.2\junit-4.13.2.jar;E:\Java_Configuration_Library\maven_repository\org\hamcrest\hamcrest-core\1.3\hamcrest-core-1.3.jar;E:\Java_Configuration_Library\maven_repository\org\projectlombok\lombok\1.18.30\lombok-1.18.30.jar;E:\Java_Configuration_Library\maven_repository\log4j\log4j\1.2.17\log4j-1.2.17.jar" com.intellij.rt.junit.JUnitStarter -ideVersion5 -junit4 com.wdw.dao.UserMapperTest,getUserList log4j:WARN No appenders could be found for logger (org.apache.ibatis.logging.LogFactory). log4j:WARN Please initialize the log4j system properly. log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info. java.lang.ExceptionInInitializerError at com.wdw.dao.UserMapperTest.getUserList(UserMapperTest.java:14) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:568) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56) at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306) at org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100) at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63) at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329) at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293) at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306) at org.junit.runners.ParentRunner.run(ParentRunner.java:413) at org.junit.runner.JUnitCore.run(JUnitCore.java:137) at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69) at com.intellij.rt.junit.IdeaTestRunner$Repeater$1.execute(IdeaTestRunner.java:38) at com.intellij.rt.execution.junit.TestsRepeater.repeat(TestsRepeater.java:11) at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:35) at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:232) at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:55) Caused by: org.apache.ibatis.exceptions.PersistenceException: ### Error building SqlSession. ### The error may exist in com/wdw/dao/UserMapper.xml ### The error occurred while processing mapper_resultMap[UserMap] ### Cause: org.apache.ibatis.builder.BuilderException: Error parsing SQL Mapper Configuration. Cause: org.apache.ibatis.builder.BuilderException: Error parsing Mapper XML. The XML location is 'com/wdw/dao/UserMapper.xml'. Cause: org.apache.ibatis.builder.BuilderException: Error resolving class. Cause: org.apache.ibatis.type.TypeException: Could not resolve type alias 'user'. Cause: java.lang.ClassNotFoundException: Cannot find class: user at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:30) at org.apache.ibatis.session.SqlSessionFactoryBuilder.build(SqlSessionFactoryBuilder.java:80) at org.apache.ibatis.session.SqlSessionFactoryBuilder.build(SqlSessionFactoryBuilder.java:64) at com.wdw.utils.MybatisUtils.<clinit>(MybatisUtils.java:22) ... 28 more Caused by: org.apache.ibatis.builder.BuilderException: Error parsing SQL Mapper Configuration. Cause: org.apache.ibatis.builder.BuilderException: Error parsing Mapper XML. The XML location is 'com/wdw/dao/UserMapper.xml'. Cause: org.apache.ibatis.builder.BuilderException: Error resolving class. Cause: org.apache.ibatis.type.TypeException: Could not resolve type alias 'user'. Cause: java.lang.ClassNotFoundException: Cannot find class: user at org.apache.ibatis.builder.xml.XMLConfigBuilder.parseConfiguration(XMLConfigBuilder.java:122) at org.apache.ibatis.builder.xml.XMLConfigBuilder.parse(XMLConfigBuilder.java:99) at org.apache.ibatis.session.SqlSessionFactoryBuilder.build(SqlSessionFactoryBuilder.java:78) ... 30 more Caused by: org.apache.ibatis.builder.BuilderException: Error parsing Mapper XML. The XML location is 'com/wdw/dao/UserMapper.xml'. Cause: org.apache.ibatis.builder.BuilderException: Error resolving class. Cause: org.apache.ibatis.type.TypeException: Could not resolve type alias 'user'. Cause: java.lang.ClassNotFoundException: Cannot find class: user at org.apache.ibatis.builder.xml.XMLMapperBuilder.configurationElement(XMLMapperBuilder.java:123) at org.apache.ibatis.builder.xml.XMLMapperBuilder.parse(XMLMapperBuilder.java:95) at org.apache.ibatis.builder.xml.XMLConfigBuilder.mapperElement(XMLConfigBuilder.java:378) at org.apache.ibatis.builder.xml.XMLConfigBuilder.parseConfiguration(XMLConfigBuilder.java:120) ... 32 more Caused by: org.apache.ibatis.builder.BuilderException: Error resolving class. Cause: org.apache.ibatis.type.TypeException: Could not resolve type alias 'user'. Cause: java.lang.ClassNotFoundException: Cannot find class: user at org.apache.ibatis.builder.BaseBuilder.resolveClass(BaseBuilder.java:118) at org.apache.ibatis.builder.xml.XMLStatementBuilder.parseStatementNode(XMLStatementBuilder.java:76) at org.apache.ibatis.builder.xml.XMLMapperBuilder.buildStatementFromContext(XMLMapperBuilder.java:138) at org.apache.ibatis.builder.xml.XMLMapperBuilder.buildStatementFromContext(XMLMapperBuilder.java:131) at org.apache.ibatis.builder.xml.XMLMapperBuilder.configurationElement(XMLMapperBuilder.java:121) ... 35 more Caused by: org.apache.ibatis.type.TypeException: Could not resolve type alias 'user'. Cause: java.lang.ClassNotFoundException: Cannot find class: user at org.apache.ibatis.type.TypeAliasRegistry.resolveAlias(TypeAliasRegistry.java:120) at org.apache.ibatis.builder.BaseBuilder.resolveAlias(BaseBuilder.java:149) at org.apache.ibatis.builder.BaseBuilder.resolveClass(BaseBuilder.java:116) ... 39 more Caused by: java.lang.ClassNotFoundException: Cannot find class: user at org.apache.ibatis.io.ClassLoaderWrapper.classForName(ClassLoaderWrapper.java:196) at org.apache.ibatis.io.ClassLoaderWrapper.classForName(ClassLoaderWrapper.java:89) at org.apache.ibatis.io.Resources.classForName(Resources.java:261) at org.apache.ibatis.type.TypeAliasRegistry.resolveAlias(TypeAliasRegistry.java:116) ... 41 more 进程已结束,退出代码为 -1
解决方式
由于使用前三种,本人都尝试过,都可成功运行
可为什么使用注解生成别名就会失败,在查阅官方文档和大量博客也找不到这个问题的解决方案
最后将UserMapper.xml的其他未使用到的sql语句全部注释,想让项目干净一点,只保留查询所有用户的sql语句
<?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"> <!-- namespace=绑定一个对应的Dao/Mapper接口 --> <mapper namespace="com.wdw.dao.UserMapper"> <resultMap id="UserMap" type="com.wdw.bean.User"> <!--mybatis数据库中的字段,property实体类中的属性--> <result column="u_id" property="id"/> <result column="u_name" property="name"/> <result column="u_pwd" property="password"/> </resultMap> <!--select查询语句--> <!--获取所有的用户--> <!-- <select id="getUserList" resultType="user" resultMap="UserMap">--> <select id="getUserList" resultType="use" resultMap="UserMap"> select * from mybatis.user; </select> <!-- <!–根据id查询用户信息–> <select id="getUserById" resultType="map" parameterType="int" resultMap="UserMap"> select * from mybatis.user where u_id = #{id}; </select> <!–添加单个用户–> <insert id="addUser" parameterType="user"> insert into mybatis.user (u_id, u_name, u_pwd) values (#{id}, #{name}, #{password}) </insert> <!–根据id修改用户–> <update id="updateUserById" parameterType="user"> update mybatis.user set u_name=#{name}, u_pwd =#{password} where u_id = #{id} </update> <!–根据id删除用户–> <select id="deleteUser" parameterType="map"> delete from mybatis.user where u_id=#{id} </select>--> </mapper>
结果查询成功
后面再看一下注释掉的内容,官方文档上并未做出解释,个人猜测是两个别名,产生了分支问题,映射器无法识别该用哪一个,所以报错
希望此博客能够帮助大家解决问题