当前位置:网站首页>[explanation of JDBC and internal classes]

[explanation of JDBC and internal classes]

2022-07-07 07:05:00 DJL_ new_ life

( Click jump )

java Learning column

LeetCode Brush topic column


JDBC And internal classes

JDBC

JDBC Routine code , modify excuteUpdate(), Inquire about excuteQuery()

all Java Operating relational databases , No matter what kind of database , The routine is the same .JPA、MyBatis All are JDBC Encapsulation .


Java.sql The next interface

  1. Acquisition data source DataSource , Configure the connection address , user name 、 Password etc.
  2. Get the connection object , Is to send a network request , Establish a connection to the database Connection
  3. Access to perform SQL The object of PreparedStatement object , Packaged SQL sentence

Connection connection = dataSource.getConnection();

String sql = “select password from user where username = ?”;

PreparedStatement statement = connection.prepareStatement(sql);

statement.setString(1,“ full name ”);

  1. Perform an update operation executeUpdate => int The number of rows affected by this update

​ Execute the query executeQuery => Result Result set

ResultSet resultSet = statement.executeQuery();

  1. Traversal result set ResultSet object , Every time you call next Method , Just take a row of data from the result set resule.getXX(“ Name ”) => Get the specific attribute value of the data in this line

while(resultSet.next())

  1. After the operation close resource ,resultSet,Connection object

Acquisition data source Yes Two ways :

One is DataSource The way ( What is actually used )

The other is DriverManager( It is not recommended to use )

DataSource :

Create... Internally Connection Object's connection pool , “ pool ”: Resource reuse

When one Connection Object call close After method He's not really closed , This object will be DataSource Recycling , Enter the connection pool .

If there are other users who need to establish a connection , Instead of creating a new connection , If there are idle connections in the connection pool , Use this connection directly .

The establishment and destruction of database connections are still time-consuming and resource consuming


DriverManager Class to get Connection Connect , Can't be reused , Every time you release resources after use , adopt connection.close() Is to close the physical connection


Specific implementation SQL There are also two ways for the object of ,

One is PreparedStatement object ( Recommended )

The other is Statement object


Statement : Simple to perform without parameters SQL sentence

PreparedStatement:

Used to execute with or without parameters SQL sentence

SQL Statements are precompiled in the database system

Execution faster than Statement object


Inner class

The so-called inner class , It is the operation of nesting one class into another class

It's just a way of Inner class A property in the current class

Inner class It is divided into :

  1. Member inner class
  2. Static inner class
  3. Method inner class
  4. Anonymous inner class (Lambda The predecessor of expression )

1 and 2 Are defined in the class , 3 and 4 Is defined in the method area

Reason for existence of inner class :

  1. Internal and external classes can easily access each other's private domains ( Properties and methods )
  2. Inner classes can be used for The exterior of the external class is completely hidden ( Treat internal classes as attributes of external classes ) Access modifier private < default < protected < public Inner classes can use private keyword
  3. Inner classes can implement multiple inheritance in a disguised form ( Understanding can )

Member inner class

1、 Member inner class : Do not use... Inside an external class static The inner class defined by keyword is the inner class of member . Analogy between member properties and member methods - The inner class of a member needs to depend on the outer class object ( First there are external class objects , There are inner class objects )

There are two ways to generate objects within a member class :

  1. Generated inside the external class Member inner class object : It's no different from ordinary classes . Inner class name Internal class reference = new Inner class ();
  2. If the internal class pair Externally visible ( No private Decorated inner class ). Create an inner class object outside the outer class , External class name . Inner class name Internal class reference = new External class ().new Inner class (); eg: Outter.Inner inner = new Outter().new Inner();

2、 The inner class of a member depends on the object of the outer class , First generate the external class object , Then the inner class object is generated - Analogy to member properties or member methods .

Member methods can access instance variables and static variables in classes , But you can't define static variables

Static methods can access static variables in classes , Member variables are not accessible

3、 The inner class of a member can directly access the private properties of the outer class

problem 1:

Member inner class Access to static fields in external classes Can I define a static field in the current inner class ?

answer : You can access static fields in external classes , Because the inner class of the member already has the object of the outer class , There are external class objects , Of course, you can access static properties

You cannot define static fields in the current inner class . If possible , The static properties of the inner class of a member can be called without generating an object , This sum The inner class of a member must depend on the outer class object to generate It's contradictory .

Static inner class

Use static keyword A class defined inside another class —— Static methods or properties

The biggest difference between static inner classes and member inner classes is : Static inner classes do not require objects of outer classes , And external classes are relatively independent , It's just an internal definition of an external class .

The static inner class can only access the static domain of the outer class , No external class objects , Cannot directly access the member domain of an external class

problem : Can a static inner class define its own member domain ?

Sure , A static inner class is a normal class , It's just inside a class


Summary :

The inner class of a member can access all domains of the outer class ( member , static state ), Because the inner class of a member depends on the object of the outer class , You cannot have your own static domain .

Static inner class You can have your own member domain , But you can't directly access the member domain of an external class ( No external class objects )


Method inner class

Is a class defined inside a method

public class Main{
    
    public void fun(){
    
        // Method inner class 
        class test{
    
            
        }
    }
}

Be careful :

  1. Method inner classes cannot use any permission modifiers ( This class has no methods )
  2. Completely hidden from the outside ( External to external classes )
  3. The inner class should use the formal parameters or local variables of the method , The variable must be implicit Of final Statement ( Method internal classes should use formal parameters or local variables in external methods , Only read right , Can't modify )
  4. If the local variables in the method are read in the internal class of the method ( Formal parameters or local variables ) This local variable cannot be modified ( Cannot be modified not only in Inner Classes , Nor in the method modify )
  5. Method inner class cannot define static Static domain ( Because static variables cannot be defined in methods )

Anonymous inner class

Defined in method ( Formal or actual parameters in methods )—— Arguments are used more

No permission modifiers , Not even the class name

Anonymous inner classes are also a kind of method inner classes , Most commonly used in method parameters

interface IMessage{
    
    void getMag(String msg);
}
public class Main{
    
    public static void main(String[] args){
    
        fun(new IMessage(){
    
            @Override
           public void getMag(String msg){
    
               
           } 
        });
    }
}

The interface cannot directly instantiate the , So here we are new Yes. IMessage Subclass of interface , But this subclass is only used in fun Method


Lambda expression

2008 year JDK8 Release , An epoch-making version

Hadoop Map Reduce There are all kinds of Lambda Use of expressions

Functional programming ideas —》 Scala

java This object-oriented definition is too cumbersome , When dealing with various mathematical operations , Frequent need to define classes , object , Methods and so on


JDK8 after , In the interface default Common method .JDK8 Before , There are only global constants and abstract methods in the interface

default Keyword the method defined in the interface is a common method ( Don't omit ), Subclasses do not need to override .

Don't write default Think of it as an abstract method

Not commonly used , Generally, it is used to expand methods in the interface of the modified ancient version


Functional interface : An interface has and has only one abstract method ( Ordinary methods do not affect ), This kind of interface is called functional interface

Use @FunctionaInterface To check whether the current interface is a functional interface


Lambda The predecessor of expression —— Anonymous inner class

fun(()->{
    
	...
});

Be able to use Lambda The premise of the expression is Interfaces must be functional , There is only one abstract method


Lambda Four cases of expressions

1 No return value no parameter

interface NoParaNoReturn{
    
    void test();
}
public static void main(String[] args){
    
    NoParaNoReturn d = ()->{
    // Inside the braces is the method body code  
        System.out.println(" No return value , No parameter ");
    };
    d.test();// What is called is after overwriting   Of test Method 
}

The rules 1: If the method body has only one line of code , It can be omitted {};

    NoParaNoReturn d = ()->System.out.println(" No return value , No parameter ");

2 No return value, parameter

interface NoParaNoReturn{
    
    void test(int a);
}
public static void main(String[] args){
    
    NoParaNoReturn d = (int x)->{
    // Inside the braces is the method body code  
        x += 10;
        System.out.println(" No return value , No parameter ");
    };
    d.test();// What is called is after overwriting   Of test Method 
}

The rules 2 : If there is only one parameter of the method body , You can omit parentheses , Type should also be omitted

The rules 3 : It can be omitted Lambda The type of parameter in the expression , If type is omitted , Need to omit

    NoParaNoReturn d = x->{
    
        x += 10;
        System.out.println(" No return value , No parameter ");
    };

3 There is a return value No parameter

interface NoParaNoReturn{
    
    int test();
}
public static void main(String[] args){
    
    NoParaNoReturn d = ()->{
    // Inside the braces is the method body code  
        int a = 10;
        int b = 10;
        return a+b;
    };
    System.out.println(d.test());// What is called is after overwriting   Of test Method 
}

The rules 4: If the abstract method has a return value And the overridden method body has only one line , At this point, the braces of the method body ,return All can be omitted

    NoParaNoReturn d = ()-> 10+10;

4 There are return values and parameters

interface NoParaNoReturn{
    
    int test(int a,int b);
}
public static void main(String[] args){
    
    NoParaNoReturn d = (x,y)-> x+=y;
    System.out.println(d.test(10,20));// What is called is after overwriting   Of test Method 
}

If it helps you , Please give me a compliment .

原网站

版权声明
本文为[DJL_ new_ life]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207070309416457.html