MyBatis интерфейс маппер - PullRequest
       76

MyBatis интерфейс маппер

0 голосов
/ 24 февраля 2020

Что не так с этой конфигурацией? Попробуйте использовать интерфейс вместо xml конфигурации? Как я могу это сделать? Не могу найти учебник ... Я получил Причина: java .io.IOException: Не удалось найти ресурс Student_mapper. Расположение моих папок по умолчанию. Student-mapper. java в папке "src / main / java". Или как я могу сделать это, используя только bean configurarion только с аннотациями? Без xml

Вот мой код:

Student_mapper

public interface Student_mapper {

    final String getAll = "SELECT * FROM STUDENT";
    final String getById = "SELECT * FROM STUDENT WHERE ID = #{id}";
    final String deleteById = "DELETE from STUDENT WHERE ID = #{id}";
    final String insert = "INSERT INTO STUDENT (NAME, BRANCH, PERCENTAGE, PHONE, EMAIL ) VALUES (#{name}, #{branch}, #{percentage}, #{phone}, #{email})";
    final String update = "UPDATE STUDENT SET EMAIL = #{email}, NAME = #{name}, BRANCH = #{branch}, PERCENTAGE = #{percentage}, PHONE = #{phone} WHERE ID = #{id}";

    @Select(getAll)
    @Results(value = {
            @Result(property = "id", column = "ID"),
            @Result(property = "name", column = "NAME"),
            @Result(property = "branch", column = "BRANCH"),
            @Result(property = "percentage", column = "PERCENTAGE"),
            @Result(property = "phone", column = "PHONE"),
            @Result(property = "email", column = "EMAIL")
    })

    List getAll();

    @Select(getById)
    @Results(value = {
            @Result(property = "id", column = "ID"),
            @Result(property = "name", column = "NAME"),
            @Result(property = "branch", column = "BRANCH"),
            @Result(property = "percentage", column = "PERCENTAGE"),
            @Result(property = "phone", column = "PHONE"),
            @Result(property = "email", column = "EMAIL")
    })

    Student getById(int id);

    @Update(update)
    void update(Student student);

    @Delete(deleteById)
    void delete(int id);

    @Insert(insert)
    @Options(useGeneratedKeys = true, keyProperty = "id")
    void insert(Student student);
}

Основной класс

public class Annotations_Example {

    public static void main(String args[]) throws IOException{

        Reader reader = Resources.getResourceAsReader("SqlMapConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        SqlSession session = sqlSessionFactory.openSession();
        session.getConfiguration().addMapper(Student_mapper.class);

        Student_mapper mapper = session.getMapper(Student_mapper.class);

        //Create a new student object
        Student student = new Student();

        //Set the values
        student.setName("zara");
        student.setBranch("EEE");
        student.setEmail("zara@gmail.com");
        student.setPercentage(90);
        student.setPhone(123412341);

        //Insert student data
        mapper.insert(student);
        System.out.println("record inserted successfully");
        session.commit();
        session.close();

    }

}

SQLMapConfig. xml в папке ресурсов

<?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>

    <typeAliases>
        <typeAlias alias = "Student" type = "Student"/>
    </typeAliases>

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

            <dataSource type = "POOLED">
                <property name = "driver" value = "org.postgresql.Driver"/>
                <property name = "url" value = "jdbc:postgresql://localhost:5432/postgres"/>
                <property name = "username" value = "postgres"/>
                <property name = "password" value = "postgres"/>
            </dataSource>

        </environment>
    </environments>

    <mappers>
        <mapper resource = "Student_mapper.java"/>
    </mappers>

</configuration>

1 Ответ

1 голос
/ 24 февраля 2020

Вместо смешивания конфигурации xml и java вы можете использовать только конфигурацию java.

//Create data Source

 public DataSource getDataSource() {
        DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
        dataSourceBuilder.driverClassName("");
        dataSourceBuilder.url("");
        dataSourceBuilder.username("");
        dataSourceBuilder.password("");
        return dataSourceBuilder.build();   



//Inject dataSourec to SqlSessionFactory
public SqlSessionFactory sqlSessionFactory() throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(getDataSource());
        return factoryBean.getObject();   

//inject SqlSessionFactory to Mapper Suppose
public MapperFactoryBean<Object it can be return type> yourMapper() throws Exception {
        MapperFactoryBean<YourMapper> factoryBean = new MapperFactoryBean<>(YourMapper.class);
        factoryBean.setSqlSessionFactory(sqlSessionFactory());
        return factoryBean;
    }   

Затем использовать объект yurMapper для вызова функции, определенной внутри него.

...