Mybatis ---- JNDI data source

Last 👉: Mybatis - mybatis multi table query many to many

🚴 hello everyone! I am short-sighted and down-to-earth. This series is mainly to record my MyBatis learning notes. This article is mainly to learn JNDI data sources
Only action can lift all your uneasiness

1. JNDI overview and principle

JNDI : Java Naming and Directory Interface. It is a set of specifications launched by SUN company. It belongs to one of java EE technologies. Its purpose is to imitate the registry in windows system. You can then register the data source in the server

When we open the above registry, no matter where we click, it will have a name and value, and double-click the value, it will have a value name and data, so its name and data will become a structure called key value, but there will also be heavy here, as shown in the flags in the figure below. Click to open the values in it 👇:


How can the above two ensure no weight finding? Then, the analysis is shown in the figure below 👇:

(analyze the above figure: first of all, since it imitates the Windows registry, the Windows registry is actually a Map structure. In this structure, it will have key value pairs, that is, key and value. We are not sure about the next key, but we know that the value is stored in data, and the object in JNDI. Through the analysis of the registry just now, it will have repetitive keys, that is, using only one key is We can't decide, but we can copy the project name and paste it. We can find that we only see SoundSentry, and then there is a flag in it, and the value of flags is 2, but we don't see a large piece of content in front of SoundSentry, the same as the other one. So we can see that JDNI first simulates the Windows registry, and the Windows registry shows that there is a path in front of it, and then the name is added behind it. So we say that if we distinguish only by name, that is, by flags, it is obviously impossible to determine who corresponds to whom, but if I add his only path in front, At this time, you can distinguish which data corresponds to. Therefore, the key stores the path and name. The path is what we call Directory, and then the name is Naming. Therefore, JDNI is stored in this way.)

(in our Tomcat server, a Map will be prepared for us as soon as the Tomcat server is started. Then, the key of the Map is a string and the value of the Map is an Object, which means that we can store everything in it. Then, we just need to write some objects in it according to the regulations. The Directory part of the key here is fixed, and then the name can be saved by ourselves designated. We can also specify what objects to store next. The way of specifying is through the configuration file.)

2. JNDI builds maven's war project

Then we can start to work on the code after understanding. First of all, can our previous java project realize the whole function? Obviously, we can't, so next we need to create a maven war project

First create the maven project, as shown in the figure 👇:


After creating it, we found that its directory does not use java or our resources 👇:

So we need to build the corresponding directories first, and then turn them into source files, resource files and so on

Then, as shown in the figure below, we have completed the creation

Next, we can copy everything under the src directory of the previous project of POOLED and UNPOOLED connection pool in our school, and then put POM We have to import XML at the same time, and then copy it in the past two 👇:

Then the preparation of the project will be ok

3. Test the use and details of JNDI data source

If you want to use JDNI, you must create a new folder in the webapp directory 👇:

Then create a new context in it XML configuration file

<?xml version="1.0" encoding="UTF-8"?>
<Context>
<!-- 
<Resource 
name="jdbc/mybatis"						        Name of the data source
type="javax.sql.DataSource"						Data source type
auth="Container"								Data source provider
maxActive="20"									Maximum number of activities
maxWait="10000"									Maximum waiting time
maxIdle="5"										Maximum idle number
username="root"									user name
password="1234"									password
driverClassName="com.mysql.jdbc.Driver"			Driver class
url="jdbc:mysql://localhost:3306/mybatis" 	     Connection url string
/>
 -->
<Resource 
name="jdbc/mybatis"
type="javax.sql.DataSource"
auth="Container"
maxActive="20"
maxWait="10000"
maxIdle="5"
username="root"
password="root"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/mybatis"
/>
</Context>

You can see that there is a Context tag and then a Resource tag. You can see that the content of name in it uses a name such as mybatis under jdbc. This name is the name analyzed above. You can specify it yourself, so I will specify it here as mybatis

type: This is what kind of object we want to save.

auth: the provider is a Container, that is, it is provided by a Container. The Container here refers to the Container provided by Tomcat

maxActive: that is, the maximum active connection is 20

maxWait: the maximum waiting time is 10000 seconds,

maxIdle: the maximum number of idle is 5

The last four are the necessary information to connect to the database

Next, modify the content of SqlMapConfig and specify the data source

<?xml version="1.0" encoding="UTF-8"?>
<!-- Import constraints -->
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <typeAliases>
        <package name="monster.zf.domain"></package>
    </typeAliases>
    <!-- to configure mybatis Environment -->
    <environments default="mysql">
        <!-- to configure mysql Environment -->
        <environment id="mysql">
            <!-- How to configure transaction control -->
            <transactionManager type="JDBC"></transactionManager>
            <!-- Configure the necessary information to connect to the database  type Property indicates whether to use a data source (connection pool)-->
            <dataSource type="JNDI">
                <property name="data_source" value="java:comp/env/jdbc/mybatis"/>
            </dataSource>
        </environment>
    </environments>

    <!-- appoint mapper Location of the configuration file -->
    <mappers>
        <mapper resource="monster/zf/dao/UserDao.xml"/>
    </mappers>
</configuration>


From the above figure, we can see that we originally wrote it through the properties file or externally, but now we specify a file called data_source, and this value, the next one is our context The name you see in XML, and the front is its path, which is fixed and can't be modified. That is to say, as long as you write according to this standard, he can use it

Then we can deploy our application

Then start Tomcat and a Helloworld welcome interface will pop up, that is, index JSP content. At this time, the test class we want to run before cannot run. The reason is that our test class has not passed the Tomcat server, that is, there is no Tomcat server to prepare this map for us. Because you don't use the Tomcat server at all, you can't get the object defined in it. At this time, it's also very simple when we want to use it for web applications, We can move the code in the test class to JSP for use 👇:

<%@ page import="java.io.InputStream" %>
<%@ page import="org.apache.ibatis.io.Resources" %>
<%@ page import="org.apache.ibatis.session.SqlSessionFactoryBuilder" %>
<%@ page import="org.apache.ibatis.session.SqlSessionFactory" %>
<%@ page import="org.apache.ibatis.session.SqlSession" %>
<%@ page import="monster.zf.domain.User" %>
<%@ page import="java.util.List" %>
<%@ page import="monster.zf.dao.UserDao" %>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="utf-8"%>
<html>
<body>
<h2>Hello World!</h2>
<%
    //1. Read the configuration file
    InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
    //2. Create SqlSessionFactory factory
    SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
    SqlSessionFactory factory = builder.build(in);
    //3. Use factory to produce SqlSession object
    SqlSession sqlSession = factory.openSession();
    //4. Use SqlSession to create the proxy object of Dao interface
    UserDao userDao = sqlSession.getMapper(UserDao.class);
    //5. Use the proxy object to execute the method
    List<User> users = userDao.findAll();
    for(User user : users){
        System.out.println(user);
    }
    //6. Release resources
    sqlSession.close();
    in.close();

%>
</body>
</html>

Then restart the server and pop up the page. At the same time, we can find the data we want to check on the console. Then this is the use of JDNI 👇:

Next 👉 MyBatis---- Mybatis deferred loading policy

This blog is over. Thank you very much for reading 🙏, In the next article, we'll learn about Mybatis's strategies to implement delay. If it's helpful to you, you can give it a favor or pay attention to it 😬

Tags: Mybatis

Posted by jeanne on Thu, 05 May 2022 04:55:04 +0300