javaweb

Socket

套接字,计算机之间进行通信的方式

public class Main{
    public static void main(String[] args) throws Exception{
        new ServerSocket(8080).accept();
        System.out.println("连接成功");
    }
}

class Client{
    public static void main(String[] args) throws Exception{
        new Socket("localhost",8080);
        System.out.println("连接服务端");
    }
}

利用Socket可以传文件,传数据,结合IO流

JDBC

Java与数据库的连接的桥梁或者插件

public class Main {
    public static void main(String[] args) throws Exception{
        ResultSet set = DriverManager.getConnection("jdbc:mysql://localhost:3306/study", "root", "123456").createStatement().executeQuery("select * from aoa_attachment_list");
        while (set.next()){
            System.out.println(set.getString(2));
        }
    }
}

Mybatis

代替JDBC

MyBatis中文网https://mybatis.net.cn/configuration.html)

image-20220706175329706

pom.xml

<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.10</version>
</dependency>

MybatisUtil

public class MybatisUtil {

    //在类加载时就进行创建
    private static SqlSessionFactory sqlSessionFactory;
    static {
        try {
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(new FileInputStream("mybatis-config.xml"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取一个新的会话
     * @param autoCommit 是否开启自动提交(跟JDBC是一样的,如果不自动提交,则会变成事务操作)
     * @return SqlSession对象
     */
    public static SqlSession getSession(boolean autoCommit){
        return sqlSessionFactory.openSession(autoCommit);
    }
}

Main.java

public class Main {
    public static void main(String[] args) {
        try (SqlSession sqlSession = MybatisUtil.getSession(true)){
            TestMapper testMapper = sqlSession.getMapper(TestMapper.class);
            List<Student> student = testMapper.selectStudent();
            student.forEach(System.out::println);
        }
    }

}

TestMapper.java

public interface TestMapper {
    @Select("select * from student")
    List<Student> selectStudent();
}

Student.java

@Data
public class Student {
    int id;
    String name;
    int age;

    @Override
    public String toString() {
        return "姓名 "+name+" 年龄 "+age;
    }
}

posted @ 2022-07-07 16:12  鱼子酱caviar  阅读(24)  评论(0)    收藏  举报